Open file in a relative location in Python


Suppose python code is executed in not known by prior windows directory say 'main' , and wherever code is installed when it runs it needs to access to directory 'main/2091/data.txt' .

how should I use open(location) function? what should be location ?

Edit :

I found that below simple code will work..does it have any disadvantages ?

10/22/2018 1:09:44 PM

With this type of thing you need to be careful what your actual working directory is. For example, you may not run the script from the directory the file is in. In this case, you can't just use a relative path by itself.

If you are sure the file you want is in a subdirectory beneath where the script is actually located, you can use __file__ to help you out here. __file__ is the full path to where the script you are running is located.

So you can fiddle with something like this:

import os
script_dir = os.path.dirname(__file__) #<-- absolute dir the script is in
rel_path = "2091/data.txt"
abs_file_path = os.path.join(script_dir, rel_path)
8/23/2011 6:59:31 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow