1、复制文件到指定文件夹
#srcfile 需要复制、移动的文件
#dstpath 目的地址
def mycopyfile(srcfile,dstpath): # 复制函数
if not os.path.isfile(srcfile):
print ("%s not exist!"%(srcfile))
else:
fpath,fname=os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.copy(srcfile, dstpath + fname) # 复制文件
print (“copy %s -> %s”%(srcfile, dstpath + fname))
src_dir = ‘./’
dst_dir = ‘./copy/’ # 目的路径记得加斜杠
src_file_list = glob(src_dir + ‘*’) # glob获得路径下所有文件,可根据需要修改
for srcfile in src_file_list:
mycopyfile(srcfile, dst_dir) # 复制文件
2、移动文件到指定文件夹
#srcfile 需要复制、移动的文件
#dstpath 目的地址
def mymovefile(srcfile,dstpath): # 移动函数
if not os.path.isfile(srcfile):
print ("%s not exist!"%(srcfile))
else:
fpath,fname=os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.move(srcfile, dstpath + fname) # 移动文件
print (“move %s -> %s”%(srcfile, dstpath + fname))src_dir = ‘./’
dst_dir = ‘./move/’ # 目的路径记得加斜杠
src_file_list = glob(src_dir + ‘*’) # glob获得路径下所有文件,可根据需要修改
for srcfile in src_file_list:
mymovefile(srcfile, dst_dir) # 移动文件
#文件、文件夹的移动、复制、删除、重命名
#导入shutil模块和os模块
import shutil,os#复制单个文件
shutil.copy(“C:\a\1.txt”,“C:\b”)#复制并重命名新文件
shutil.copy(“C:\a\2.txt”,“C:\b\121.txt”)
#复制整个目录(备份)
shutil.copytree(“C:\a”,“C:\b\new_a”)#删除文件
os.unlink(“C:\b\1.txt”)
os.unlink(“C:\b\121.txt”)
#删除空文件夹
try:
os.rmdir(“C:\b\new_a”)
except Exception as ex:
print(“错误信息:”+str(ex))#提示:错误信息,目录不是空的
#删除文件夹及内容
shutil.rmtree(“C:\b\new_a”)#移动文件
shutil.move(“C:\a\1.txt”,“C:\b”)
#移动文件夹
shutil.move(“C:\a\c”,“C:\b”)#重命名文件
shutil.move(“C:\a\2.txt”,“C:\a\new2.txt”)
#重命名文件夹
shutil.move(“C:\a\d”,“C:\a\new_d”)