0

I'm attempting to make a python package of the following hierarchy:

\standard
    \__init__.py
    \text.txt
    \scan.py

There is a function within scan.py called parse() which opens text.txt via:

name_list = open('text.txt','r')

However when I run

from standard import *
result = scan.parse()

I get the following:

IOError: [Errno 2] No such file or directory: '/text.txt'
0

1 Answer 1

2

Python has the funny variable __file__ which is the name of the file containing the running code. Your code is looking in the current working directory instead.

Use this to open your file:

open(os.path.join(os.path.dirname(__file__), 'text.txt'), 'r')

Docs related to special variable __file__:

http://docs.python.org/reference/datamodel.html

2
  • Why do I need to specify the entire path name if the text file is in the same directory as scan.py? Commented Jun 12, 2012 at 23:02
  • By default, the python interpreter looks in the current working directory - where you are running the entire program from. scan.py is a module within that program. This is much harder to do in other languages because they lack this special file variable. Technically, you could compute the relative path (based on the current path and the code's file's path) and use that to open the file, but that would be harder.
    – Julian
    Commented Jun 12, 2012 at 23:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.