📜  __file__ python (1)

📅  最后修改于: 2023-12-03 15:13:14.307000             🧑  作者: Mango

Python's built-in file variable

When programming in Python, you have access to a built-in variable called __file__. This variable contains the path to the current file being executed.

Usage:
print(__file__)
Output:
/path/to/your/file.py

The value of __file__ is a string containing the path to the script that is currently running. This can be useful for many different purposes, such as accessing files in the same directory as your script, or to generate relative paths.

Example:
import os

file_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(file_dir, 'example.txt')

with open(file_path, 'r') as f:
    print(f.read())

In the above example, we use the os module to get the directory name of the current file, and use it to construct a path to a text file in the same directory. We then open and read the contents of the file.

Using __file__ allows us to write more flexible and portable code, as it allows us to reference files and directories relative to the location of our script.

Conclusion:

In summary, __file__ is a powerful built-in variable in Python that allows you to easily access and manipulate files relative to the location of your script. Make sure to keep it in mind next time you're writing a Python script!