Skip to main content
 首页 » 编程设计

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

2024年10月01日7JustinYoung

这可能是重复,但无论如何与 python 中的导入直接相关。

我的目录结构如下:

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

在 sample.py 中

from utils import 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()