Anthony
Anthony

Reputation: 35958

Python path not finding text file

I have my python code in this structure:

folder:
   Procfile
   folder2:
      myprog.py
      foo.py
      somefile.txt

My Procfile contains web: python folder2/myprog.py

myprog.py contains:

import sys
sys.path.insert(0, '../')
#other code

foo.py contains:

print "about to read file"
file = open("somefile.txt", "r") 
print file.read() 
print "done reading"

I'm not able to read the file. The code never reached done reading part eventhough it prints about to read file

Upvotes: 2

Views: 1222

Answers (1)

Billy
Billy

Reputation: 5609

You can take advantage of the automatic module variable __file__ and the fact that you know somefile.txt is in the same directory as foo.py:

file = open(os.path.join(os.path.dirname(__file__), "somefile.txt"), "r") 

sys.path only determines the search path for importing modules, not where generic files will be opened from the filesystem.

Upvotes: 3

Related Questions