Path when reading an external file

Martin A. Brown martin at linux-ip.net
Mon Mar 28 11:40:07 EDT 2016


Greetings,

> In a program "code.py" I read an external file "foo.txt" supposed 
> to be located in the same directory that "code.py"
>
> python/src/code.py
> python/src/foo.txt
>
> In "code.py": f = open('foo.txt', 'r')
>
> But if I run "python code.py" in an other dir than src/ say in 
> python/, it will not work because file "foo.txt" will be searched 
> in dir python/ and not in dir python/src/
>
> I think it is possible to build an absolute path for "foo.txt" 
> using __file__ so that the program works wherever you launch 
> "python code.py"
>
> Is it the correct way to handle this problem ?

Ayup, I would say so.  My suggested technique:

  here = os.path.dirname(os.path.abspath(__file__))
  foo = os.path.join(here, 'foo.txt')
  with open(foo, 'r') as f:
      pass

Good luck,

-Martin

-- 
Martin A. Brown
http://linux-ip.net/



More information about the Python-list mailing list