用到的库os
os 库讲解见目录 os.path()
Python os.path() 模块 详解 附算例
代码
import os
here = os.path.abspath(os.path.dirname(__file__))
print("here:",here)
#获取绝对路径
abs_path = os.path.abspath(__file__)
print("当前程序文件路径:",abs_path)
dir_name = os.path.dirname(abs_path)
print("当前文件目录路径:",dir_name)
#拼接
txt_file_path = os.path.join(dir_name, 'demo.txt')
print("拼接路径1:",txt_file_path)
#拼接
txt_file_path2 = os.path.join(dir_name, "yudengwu" ,'demo.txt')
print("拼接路径2:",txt_file_path2)
输出
C:\anaconda3.7\python.exe D:/deeplearn/xuexicaogao/web/草稿.py
here: D:\deeplearn\xuexicaogao\web
当前程序文件路径: D:\deeplearn\xuexicaogao\web\草稿.py
当前文件目录路径: D:\deeplearn\xuexicaogao\web
拼接路径1: D:\deeplearn\xuexicaogao\web\demo.txt
拼接路径2: D:\deeplearn\xuexicaogao\web\yudengwu\demo.txt
Process finished with exit code 0