Files are copied or deleted in batches

The computer environment

Batch File replication

File deletion

Delete a specific file in a directory (just to the recycle bin)

Delete files (completely delete)

The computer environment

Python: Python 3.7

Windows: win10

Batch File replication

Import the required libraries

import os

import shutil

import stat





def copyFiles(sourceDir,targetDir):



List source directory files and folders

for file in os.listdir(sourceDir):

# Join the full path

sourceFile = os.path.join(sourceDir,file)

targetFile = os.path.join(targetDir,file)



If it is a file, process it

if os.path.isfile(sourceFile):

Create an empty file if the destination path does not exist and keep the directory hierarchy

if not os.path.exists(targetDir):

os.makedirs(targetDir)

If the file does not exist in the destination path or the file with the same name exists but is incomplete, then copy it, otherwise skip

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”)



# recurse if it is a folder

if os.path.isdir(sourceFile):

copyFiles(sourceFile, targetFile)

if __name__ ==”__main__”:

copyFiles(“C:/Users/fatflower/Desktop/11″,”C:/Users/fatflower/Desktop/44″,””)



File deletion

Delete a specific file in a directory (just to the recycle bin)

Import the required libraries

import os

import shutil

import stat



# delete files of the specified type in a directory, including files of the specified type in subfolders.

def removeFileInDir(sourceDir, FileTail):

for file in os.listdir(sourceDir):

File =os.path.join(sourceDir,file) # Must concatenate the full filename

#FileTail Specifies the type of file to delete

if os.path.isfile(file) and file.find(FileTail)>0:

os.remove(file)

print( file+” remove succeeded”)



# recurse if it is a folder

if os.path.isdir(file):

removeFileInDir(file, FileTail)

if __name__ ==”__main__”:

removeFileInDir(“C:/Users/fatflower/Desktop/44″,”.pdf”)

Delete files (completely delete)

Import the required libraries

import os

import shutil

import stat



Delete files completely

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”)

More technical information can be obtained from itheimaGZ