文件批量复制、删除 电脑环境 文件批量复制 文件删除 删除某目录下的特定文件(只是删除到回收站) 删除文件(彻底删除) 电脑环境 Python:Python 3.7 Windows:win10 文件批量复制 # 导入需要的库 import os import shutil import stat
def copyFiles(sourceDir,targetDir):
#列出源目录文件和文件夹 for file in os.listdir(sourceDir): #拼接完整路径 sourceFile = os.path.join(sourceDir,file) targetFile = os.path.join(targetDir,file)
#如果是文件则处理 if os.path.isfile(sourceFile): #如果目的路径不存在该文件就创建空文件,并保持目录层级结构 if not os.path.exists(targetDir): os.makedirs(targetDir) #如果目的路径里面不存在某个文件或者存在那个同名文件但是文件有残缺,则复制,否则跳过 if not os.path.exists(targetFile) or (os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))): open(targetFile, "wb").write(open(sourceFile, "rb").read()) print( targetFile+" copy succeeded")
#如果是文件夹则递归 if os.path.isdir(sourceFile): copyFiles(sourceFile, targetFile) if __name__ =="__main__": copyFiles("C:/Users/fatflower/Desktop/11","C:/Users/fatflower/Desktop/44","")
文件删除 删除某目录下的特定文件(只是删除到回收站) # 导入需要的库 import os import shutil import stat
#删除某目录下指定类型的文件,包括子文件夹中的指定类型文件(只是删除到回收站) def removeFileInDir(sourceDir, FileTail): for file in os.listdir(sourceDir): file=os.path.join(sourceDir,file) #必须拼接完整文件名 #FileTail 指定需要删除的文件类型 if os.path.isfile(file) and file.find(FileTail)>0: os.remove(file) print( file+" remove succeeded")
#如果是文件夹则递归 if os.path.isdir(file): removeFileInDir(file, FileTail) if __name__ =="__main__": removeFileInDir("C:/Users/fatflower/Desktop/44",".pdf") 删除文件(彻底删除) # 导入需要的库 import os import shutil import stat
#彻底删除文件 def delete_file(filePath): if os.path.exists(filePath): for fileList in os.walk(filePath): for name in fileList[2]: os.chmod(os.path.join(fileList[0],name), stat.S_IWRITE) os.remove(os.path.join(fileList[0],name)) shutil.rmtree(filePath) print("delete ok") else: print("no filepath")
if __name__ =="__main__": delete_file("C:/Users/fatflower/Desktop/44") |
|