在 python 中导入模块时加载文件失败

Failed to load file while importing modules in 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()

现在的错误是当我 运行 sample.py IOError: [Errno 2] No such file or directory: '../Data/stopwords.txt' 。我理解错误的症结所在,因为当我在 preprocess.py 中打印 os.getcwd() 时,我得到了 '/home/username/Main'。

但是怎么解决呢。任何帮助将不胜感激

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()
myfile = open("OpenEveningResults.csv", "a", newline="")

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