1. 使用`os.path`模块:
import os
获取当前文件的绝对路径
current_path = os.path.abspath(__file__)
获取当前文件的目录路径
directory = os.path.dirname(current_path)
获取父目录路径
parent_path = os.path.dirname(directory)
获取父目录的父目录路径
grandparent_path = os.path.dirname(parent_path)
路径连接
new_path = os.path.join(parent_path, 'config.ini')
2. 使用`sys`模块:
import sys
获取当前文件的绝对路径
current_path = os.path.abspath(__file__)
获取当前工作目录路径
working_dir = os.getcwd()
获取模块所在的路径
module_path = sys.path
3. 使用`__file__`属性:
获取当前文件的绝对路径
current_path = os.path.abspath(__file__)
获取当前文件的目录路径
directory = os.path.dirname(current_path)
4. 使用`os.getcwd()`函数:
import os
获取当前工作目录路径
working_dir = os.getcwd()
5. 使用`print`函数输出文件路径:
import os
获取当前文件的绝对路径
current_path = os.path.abspath(__file__)
输出文件路径
print(current_path)
以上方法可以帮助你获取到文件的绝对路径、目录路径或者父目录路径。请根据你的需求选择合适的方法