Path when reading an external file

ast nomail at com.invalid
Mon Mar 28 11:48:33 EDT 2016


"Martin A. Brown" <martin at linux-ip.net> a écrit dans le message de 
news:mailman.108.1459179618.28225.python-list at python.org...
>
> 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/

Ok, this is what I intended to do
Thanks for your answer 




More information about the Python-list mailing list