shutil文件操作

#复制文件:
shutil.copyfile("oldfile","newfile") #oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") #oldfile只能是文件,newfile可以是文件,也可以是目标目录
 
#复制文件夹:
shutil.copytree("olddir","newdir") #olddir和newdir都只能是目录,且newdir必须不存在
 
#重命名文件(目录)
os.rename("oldname","newname") #文件或目录都是使用这条命令
 
#移动文件(目录)
shutil.move("oldpos","newpos") 
shutil.move("D:/知乎日报/latest/一张优惠券,换你的通讯录信息,你愿意吗?.pdf", "D:/知乎日报/past/")
# 移动文件到文件夹,移动文件到文件 (srcfile需要具体到文件名;dstfile不需要具体到文件名,写成要移动的指定目录也可)
def mymovefile(srcfile, dstfile): # dstfile为文件夹或者文件
    if not os.path.isfile(srcfile):
        print("%s not exist!" % (srcfile))
    else:
        fpath, fname = os.path.split(dstfile)  # 分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)  # 创建路径
        shutil.move(srcfile, dstfile)  # 移动文件(源文件->目标文件夹或者目标文件)
        print("move %s -> %s" % (srcfile, dstfile))

# 复制源文件到目标文件 (两个输入都需要具体到文件名)
def mycopyfile(srcfile, dstfile): # dstfile为文件
    if not os.path.isfile(srcfile):
        print("%s not exist!" % (srcfile))
    else:
        fpath, fname = os.path.split(dstfile)  # 分离文件名和路径
        if not os.path.exists(fpath):
            os.makedirs(fpath)  # 创建路径
        shutil.copyfile(srcfile, dstfile)  # 复制文件(源文件名->目标文件名)
        print("copy %s -> %s" % (srcfile, dstfile))

参考链接:

上一篇:JAVA把指定文件放入压缩包


下一篇:5/18笔记