Home > Article > Backend Development > How to Open Files in the Same Directory as Your Python Script?
File Opening in Same Directory as Running Script
When working with Python scripts, reliably opening files in the same directory as the running script is crucial. However, using commands like open("Some file.txt", "r") may encounter issues if the script is executed via double-clicking in Windows.
Problematic and Reliable Techniques
Techniques that may fail include:
A reliable method is:
__location__ = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__)))
This combines the current working directory with the path derived from __file__. If __file__ is absolute, the prefix is removed. Realpath handling ensures that any symbolic links are resolved.
Opening Files
To open a file in the same directory, use the following syntax:
f = open(os.path.join(__location__, 'bundled-resource.jpg'))
This ensures that the file is located in the same directory as the running script. The technique works reliably in both Windows and Linux environments, handling double-clicking and resource bundling scenarios effectively.
The above is the detailed content of How to Open Files in the Same Directory as Your Python Script?. For more information, please follow other related articles on the PHP Chinese website!