python使用OS模块进行获取路径,路径拼接,路径判断,拷贝,删除,复制,移动,重命名
当前路径
获取当前路径
import os
#获取当前文件绝对路径
true_path_1 = os.path.abspath(__file__)
#获取当前脚本文件夹路径
file_foot_path = os.path.dirname(true_path_1)
引用同目录下文件(拼接)
区分系统与否
- 限定系统
other_path_plus = file_foot_path+'\\files\\1.txt' read_object = open(other_path_plus,mode='r',encoding='utf-8') data = read_object.read() print(data) read_object.close()
不区分系统
other_file_path = os.path.join(file_foot_path, 'files','1.txt') read_object = open(other_file_path, 'r',encoding='utf-8') data = read_object.read() print(data) read_object.close()
os参数
脚本位置
true_path_1 = os.path.abspath(__file__)
脚本上级目录
file_foot_path = os.path.dirname(true_path_1)
路径拼接
other_file_path = os.path.join(file_foot_path,'files','1.txt')
文件是否存在
os.path.exists(other_file_path)
创建文件夹
file_path = os.path.join(file_foot_path, 'files','oxox') #判断文件夹是否存在 if not os.path.exists(file_path): os.makedirs(file_path)
判断是否是文件夹
file_path = os.path.join(file_foot_path, 'files','oxox','1.png') print(file_path)
删除文件夹
dir_path = os.path.join(file_foot_path,'files','oxox') shutil.rmtree(dir_path)
拷贝文件夹
shutil.copytree('files/head_pic', file_foot_path+'\head_pic')
拷贝文件
shutil.copy('files/head_pic/Hush.png', file_foot_path+'\Hush.png')
重命名文件或者移动文件
本质是将源文件二进制填充到新文件
重命名
new_path = file_foot_path+r'\files\head_pic' shutil.move(new_path, os.path.dirname(true_path_1) + r'\head_pic2')
移动
#移动新建 shutil.move(new_path, file_foot_path+r'\head_pic2')