2

If I have a Python file called example.py that says with open('%s/data.csv' % sys.path[0]) as var_name: and data.csv is in the same directory as example.py, it works fine if I run example.py from the terminal, but when using unittest it does not work. My understanding is that when running it from the terminal, sys.path[0] gives me the path to the file being run (example.py), and thus if data.csv and example.py are in the same directory, sys.path[0]/data.csv will correctly find data.csv. But when unittest runs, for whatever behind-the-scenes reason sys.path[0] is empty, and /data.csv is correctly NOT found.

So I was wondering what a good strategy (and perhaps some explicit code :) ) is to make this reference always work no matter what (I'm guessing without sys.path[0] but if there's something that works with that I'll take it).

I should also mention I'm on OS X 10.9.3 and using python 2.7

tscizzle
  • 11,191
  • 15
  • 54
  • 88

1 Answers1

10

just a guess but try

with open('%s/data.csv' % os.path.dirname(__file__)) as ...

or probably even preferred

 file_path = os.path.join(os.path.dirname(__file__),"data.csv")
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179