【问题标题】:Failed to load file while importing modules in python在 python 中导入模块时加载文件失败
【发布时间】:2018-03-16 20:39:21
【问题描述】:

这可能是重复,但无论如何都与 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' 。

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

【问题讨论】:

  • 在路径中使用“Data/stopwords.txt”
  • @planet260 - 我猜这不是一个好方法。我正在寻找标准解决方案。谢谢。

标签: python import relative-path


【解决方案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()

【讨论】:

  • 非常感谢。非常需要且非常有用。
  • 这是在从许多地方导入文件时将文件加载到模块中的可靠方法。我希望有一个指南可以在一个地方编译所有“正确的方法”来构建模块。
【解决方案2】:
myfile = open("OpenEveningResults.csv", "a", newline="")

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

【讨论】:

  • 不确定这是否有帮助,但希望有帮助
猜你喜欢
  • 1970-01-01
  • 2020-05-21
  • 2013-12-03
  • 2017-12-26
  • 2019-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
相关资源
最近更新 更多