import os
import sys
# os.path.abspath(__file__):当前执行文件的路径,如 D:\aaa\bbb\ccc.py
# os.path.dirname(os.path.abspath(__file__)):当前执行文件的上级路径,如 D:\aaa\bbb
# 继续向上:os.path.dirname(os.path.dirname(os.path.abspath(__file__))):D:\aaa
# 添加路径:sys.path.append
# 路径不存在则自动创建:os.makedirs(os.path.dirname(filename), exist_ok=True)
# 路径组合:os.path.join(path1,path2,path3……)
# 案例
filepath = 'file/123.mp4' # 再当前执行文件的目录的子文件file文件夹创建123.MP4文件
os.makedirs(os.path.dirname(filepath), exist_ok=True) # 如果file文件夹不存在,则创建file文件夹
a = os.path.abspath(__file__)
print(a) # D:\Python\python_learning\py_lujing.py
b = os.path.dirname(a)
print(b) # D:\Python\python_learning
base_path = os.path.dirname(os.path.abspath(__file__)) # 当前脚本所在路径 D:\Python\python_learning
file_path1 = base_path + "/file/info.txt" # 路径拼接方法一(只能windows):D:\Python\python_learning\file\info.txt
file_path2 = os.path.join(base_path,'file','info.txt') # 路径拼接方法二(系统兼容):D:\Python\python_learning\file\info.txt
file_path0 = os.path.join(base_path,'file') # D:\Python\python_learning\file
if os.path.exists(file_path2): # 判断文件路径是否存在
file = open(file_path2,mode='r',encoding='utf-8')
data = file.read()
file.close()
else:
os.makedirs(file_path0) # 路径不存在则创建路径,创建的是文件夹file
# 判断是否文件夹
is_dir = os.path.isdir(file_path2)
print(is_dir) # False
is_dir = os.path.isdir(file_path0)
print(is_dir) # True
import shutil
shutil.rmtree(file_path0) # 删除路径
shutil.copytree('D:\Python\python_learning\\file','D:\Python\python_learning\\file2') # 把file拷贝到file2
shutil.copy('D:\Python\python_learning\py_01.py','D:\Python\python_learning\\file') # 把py_01.py拷贝到file
shutil.copy('D:\Python\python_learning\py_01.py','D:\Python\python_learning\\file\\py_02.py') # 把py_01.py拷贝到file并命名为py_02.py
shutil.move('D:\Python\python_learning\py_lei.py','D:\Python\python_learning\py_lei2.py') # 把py_lei.py重命名为py_lei2.py
shutil.move('D:\Python\python_learning\\file','D:\Python\python_learning\\file1') # 把file重命名file1