I use the following function for opening files in Python:
def file_path(relative_path): folder = os.path.dirname(os.path.abspath(__file__)) path_parts = relative_path.split("/") new_path = os.path.join(folder, *path_parts) return new_path
I call it with a relative path, like this:
with open(file_path("my_files/zen_of_python.txt")) as f: zop = f.read()
I like it because you can use a relative path works no matter where the Python script is executed from:
folder = os.path.dirname(os.path.abspath(__file__))gets the absolute path to the folder holding the python script.
os.path.join(folder, *path_parts)gets an os-independent path to the file to open.
To further explain, let's say I have the following folder structure:
- parent_folder - example.py - my_files - zen_of_python.txt
If example.py looks like this:
with open("my_files/zen_of_python.txt") as f: zop = f.read()
Then I have to run example.py from the parent_folder directory or else it won't find
But if I open
my_files/zen_of_python.txt using the
file_path() function shown above, I can run example.py from anywhere.
One downside as @infinitezero pointed out is that you can't use an absolute path, but for my purposes, that's okay for my purposes. The script is self-contained. I'm not passing in external files when I run it.
Can anyone see any downside to this? Or does anyone have a more Pythonic way of accomplishing the same thing?