在Python中获取文件路径可以通过`os`模块来实现。以下是获取文件路径的几种常见方法:
1. 获取当前文件路径:
```python
import os
file_path = os.path.abspath(__file__) 获取当前文件的绝对路径
print("当前文件的绝对路径:", file_path)
2. 获取当前工作目录路径:
```python
import os
current_dir = os.getcwd() 获取当前工作目录路径
print("当前工作目录路径:", current_dir)
3. 获取文件的绝对路径:
```python
import os
file_path = os.path.abspath("filename.txt") 获取文件的绝对路径
print("文件的绝对路径:", file_path)
4. 获取文件所在的目录路径:
```python
import os
file_path = os.path.abspath("filename.txt")
dir_path = os.path.dirname(file_path) 获取文件所在的目录路径
print("文件所在的目录路径:", dir_path)
5. 获取父目录路径:
```python
import os
file_path = os.path.abspath("filename.txt")
parent_dir = os.path.dirname(file_path) 获取父目录路径
print("父目录路径:", parent_dir)
6. 获取父目录的父目录路径:
```python
import os
parent_dir = os.path.dirname(os.path.abspath("filename.txt"))
grandparent_dir = os.path.dirname(parent_dir) 获取父目录的父目录路径
print("父目录的父目录路径:", grandparent_dir)
7. 使用`os.path.join`连接路径:
```python
import os
dir_path = os.path.dirname(os.path.abspath("filename.txt"))
new_path = os.path.join(dir_path, "new_directory", "config.ini") 使用os.path.join连接路径
print("连接后的路径:", new_path)
8. 获取当前文件所在目录下的同级文件路径:
```python
import os
file_path = os.path.abspath("filename.txt")
parent_dir = os.path.dirname(file_path)
sibling_file_path = os.path.join(parent_dir, "sibling_file.txt") 获取同级文件路径
print("同级文件路径:", sibling_file_path)
以上方法可以帮助你在Python中获取文件路径。