前言
编写python脚本实现功能的工作中,我们常常遇到操作文件的位置问题,本文大概的列举了几种常用的方法,欢迎大家评论和补充。
获取当前文件的路径os.path.abspath(__ file __)
import os
# 可以用__file__获取当前文件的全路径
current_file_path = os.path.abspath(__file__)
print(current_file_path)
# 结果
C:\Users\admin\PycharmProjects\MyProject\Test.py
获取当前脚本文件的目录 os.path.dirname(__ file __)
import os
current_path = os.path.dirname(__file__)
print(current_path)
# 结果
C:/Users/admin/PycharmProjects/MyProject
拼接路径、获取当前文件的父目录
需进行拼接os.path.join() ,才能获取父目录
import os
pardir = os.path.pardir # 返回 .. 表示上一层目录
current_path = os.path.dirname(__file__)
join_path = os.path.join(current_path, pardir)
father_abspath = os.path.abspath(join_path)
print("pardir: ", pardir)
print("join_path: ", join_path)
print("father_abspath: ", father_abspath)
# 结果
pardir: ..
join_path: C:/Users/admin/PycharmProjects/MyProject\..
father_abspath: C:\Users\admin\PycharmProjects
文件是否存在 os.path.exists(file)
import os
file = r"C:\Users\admin\PycharmProjects\MyProject\Test.py"
if not os.path.exists(file):
print("Does not exist!")
else:
print("Exist! Please go on!")
# 结果
Exist! Please go on!