python中的IOEerror“没有这样的文件或目录” [英] IOEerror in python "No such file or directory"

查看:1303
本文介绍了python中的IOEerror“没有这样的文件或目录”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  data = file(snp_data.txt)

当我调用它时,模块工作正常分别在django项目之外;当我在django应用程序中与其他模块通话时,我会继续收到错误。

 没有这样的文件或目录为snp_data .txt'

任何想法发生了什么?

解决方案

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

  import os.path 
BASE = os.path.dirname(os .path.abspath(__ file__))

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

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



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


I am writing a django project that involves retrieving data from a table. I have a module that has the line to retrieve some data (snp_data.txt is a file on the same directory of the module):

  data = file("snp_data.txt")

While the module works well when I call it separately outside the django project; I keep getting the error below, when I call with other module within the django app.

  no such file or directory as 'snp_data.txt'

Any idea what's going on?

解决方案

You are trying to open the file in the current working directory, because you didn't specify a path. You need to use an absolute path instead:

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

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

because the current working directory is rarely the same as the module directory.

Note that I used open() instead of file(); the former is the recommended method.

这篇关于python中的IOEerror“没有这样的文件或目录”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆