python `__file__`详细介绍一下它的用法
时间: 2023-07-30 13:13:07 浏览: 55
在Python中,`__file__`是一个内置变量,用于获取当前脚本文件的路径。它表示当前模块(或脚本)的文件名。
下面是`__file__`变量的一些常见用法:
1. 获取当前脚本文件的绝对路径:
```python
import os
current_file = os.path.abspath(__file__)
print(current_file)
```
这将输出当前脚本文件的绝对路径,包括文件名。
2. 获取当前脚本文件所在的目录路径:
```python
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
print(current_dir)
```
这将输出当前脚本文件所在的目录路径,不包括文件名。
3. 构建其他文件的路径:
```python
import os
current_dir = os.path.dirname(os.path.abspath(__file__))
other_file = os.path.join(current_dir, 'other_file.txt')
print(other_file)
```
这将构建一个名为`other_file.txt`的文件的路径,该文件与当前脚本文件位于同一目录下。
需要注意的是,`__file__`变量在交互式解释器中使用时可能会引发`NameError`异常,因为在交互式解释器中没有当前脚本文件的概念。
总结来说,`__file__`变量提供了一种方便的方法来获取当前脚本文件的路径,可以用于构建其他文件的路径或进行文件操作。