Yishen Chen
Yishen Chen

Reputation: 589

IOEerror in python "No such file or directory"

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?

Upvotes: 4

Views: 7046

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121524

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.

Upvotes: 14

Related Questions