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

Sign up to request clarification or add additional context in comments.

2 Comments

Why do I need to specify the entire path name if the text file is in the same directory as scan.py?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.