python 获取文件路径
时间: 2023-08-12 09:39:25 浏览: 128
在 Python 中,获取文件路径可以使用 `os.path` 模块提供的方法。具体来说,可以使用 `os.path.abspath()` 方法获取文件的绝对路径,或者使用 `os.path.dirname()` 方法获取文件所在的目录路径。下面是两个例子:
1. 获取文件的绝对路径
```python
import os
# 以当前文件(.py文件)所在目录下的 test.txt 文件为例
file_path = "test.txt"
# 使用 os.path.abspath() 方法获取文件的绝对路径
abs_file_path = os.path.abspath(file_path)
# 输出绝对路径
print(abs_file_path)
```
上述代码会输出类似于 `C:\Users\username\project\test.txt` 的绝对路径,其中 `username` 是你的计算机用户名,`project` 是你的 Python 项目所在的目录。
2. 获取文件所在目录的路径
```python
import os
# 以当前文件(.py文件)所在目录下的 test.txt 文件为例
file_path = "test.txt"
# 使用 os.path.dirname() 方法获取文件所在目录的路径
dir_path = os.path.dirname(file_path)
# 输出目录路径
print(dir_path)
```
上述代码会输出类似于 `C:\Users\username\project` 的目录路径,其中 `username` 是你的计算机用户名,`project` 是你的 Python 项目所在的目录。
阅读全文
相关推荐














