1、獲取當前路徑
current_path1 = os.path.abspath(__file__) current_path2 = os.path.realpath(__file__)
兩種方式返回結果一樣:
D:\PythonProject\test\app01\config\read_yaml.py
D:\PythonProject\test\app01\config\read_yaml.py
2、獲取父路徑
pra_path1 = os.path.abspath(os.curdir) pra_path2 = os.path.dirname(os.path.abspath(__file__))
放回結果:
D:\PythonProject\test\app01\config
D:\PythonProject\test\app01\config
區別:
pra_path1返回的是執行文件所在文件夾,如果其他文件調用read_yaml.py,則返回其他文件的父路徑。
例如文件D:\PythonProject\test\app01\common\cc.py調用read_yaml.py,則返回D:\PythonProject\test\app01\common
pra_path2返回的是read_yaml.py文件所在文件夾,不管誰調用返回均為D:\PythonProject\test\app01\config
3、獲取父路徑的父路徑
pra_path3 = os.path.dirname(pra_path2)
4、路徑拼接
new_path = os.path.join(pra_path2,‘report’,'config.ini')
5、創建路徑
if not os.path.exists(new_path): os.makedirs(new_path)
