2017-10-05 78 views
1

这可能是重复,但无论如何直接与python中的导入有关。在python中导入模块时无法加载文件

我有一个目录结构类似如下:

Main/
sample.py 
utils/preprocess.py , __init__.py 
Data/stopwords.txt 

在sample.py

from utils import preprocess 

在preprocess.py

import codecs 
stopwords_ = codecs.open('../Data/stopwords.txt' , encoding='utf-8') 
stopwords_ = stopwords_.readlines() 

现在,当我运行样本误差。 py IOError:[Errno 2]没有这样的文件或目录:'../Data/stopwords.txt'。我理解错误的症结所在,因为当我在preprocess.py中打印os.getcwd()时,我得到'/ home/username/Main'。

但是如何解决它。任何帮助,将不胜感激

+0

在路径 – planet260

+0

@ planet260中使用“Data/stopwords.txt” - 这不是一个整洁的方式,我猜。我正在寻找标准的解决方案。谢谢 。 –

回答

1

preprocess.py中的代码假定一个特定的工作目录。你可以让这相对于preprocess.py是在目录中。

import codecs 
import os 
stopwords_file_path = os.path.join(
    os.path.dirname(__file__), 
    '../Data/stopwords.txt') 
stopwords_ = codecs.open(stopwords_file_path, encoding='utf-8') 
stopwords_ = stopwords_.readlines() 
+0

非常感谢。非常需要和非常有用。 –

0
myfile = open("OpenEveningResults.csv", "a", newline="") 

您可能需要使用不同的代码来打开或写入或读取之前创建的文件来试试。您可以使用上面的代码作为示例,因为它会创建[a]追加(追加写入文件,每次创建一个新行)CSV或Exel文件。

+0

不知道这是否有帮助,但希望它有 – Dan