【问题标题】:IOEerror in python "No such file or directory"python中的IOEerror“没有这样的文件或目录”
【发布时间】:2013-02-28 22:02:34
【问题描述】:

我正在编写一个涉及从表中检索数据的 django 项目。我有一个模块,它有一行来检索一些数据(snp_data.txt 是模块同一目录下的文件):

  data = file("snp_data.txt")

当我在 django 项目之外单独调用它时,该模块运行良好;当我使用 django 应用程序中的其他模块调用时,我不断收到以下错误。

  no such file or directory as 'snp_data.txt'

知道发生了什么吗?

【问题讨论】:

  • 您传递“snp_data.txt”的方式是相对路径 - 相对于您运行脚本的位置。
  • 我会将文本文件更改为实际路径,而不是 data = file("snp_data.txt")。应该是data = file("Path\to\snp_data.txt")

标签: python django file


【解决方案1】:

您正试图打开 当前 工作目录中的文件,因为您没有指定路径。您需要使用绝对路径:

import os.path
BASE = os.path.dirname(os.path.abspath(__file__))

data = open(os.path.join(BASE, "snp_data.txt"))

因为当前工作目录很少与模块目录相同。

请注意,我使用了open() 而不是file();前者是推荐的方法。

【讨论】:

    猜你喜欢
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2021-06-24
    相关资源
    最近更新 更多