Using Python to copy multi directory files
Recently, due to work needs, I wanted to find a software that can copy files from multiple directories at the same time. I found a domestic software of "file batch copy tool", which can meet my multi directory file copy requirements, but it needs to be charged. Finally, I decided to implement it in Python by myself. Recently, I was learning Python and just practiced my hand.
Read source file list file
Since there may be multiple files to be copied, these files to be copied are compiled into a source file list file. This is a text file. I named it "source file list. lst". The file content is the absolute path of all files to be copied, one line for each file, as shown below.
D:\source file\1.docx D:\source file\2.xlsx D:\source file\3.pptx
Define the readsourcelistfile function to read the file list file, as follows:
# Read the source file list and return the file absolute path list def readsourcelistfile(filename): if not os.path.isfile(filename): print("Source file list file error!") return None try: f = open(filename, 'r') srclist = f.readlines() n = 0 for name in srclist: print(name.strip()) name = name.replace('\\', '\\\\').strip() if not os.path.isfile(name): print("source file%s Can't find!" % name) return None srclist[n] = name n = n + 1 print("There are in the source file list%s Files" % len(srclist)) return srclist finally: if f: f.close()
This function finally returns the list of absolute paths of all files to be copied. It should be noted that because there is a backslash "\" in the absolute path of the file in the "source file list. lst", Python should be escaped, otherwise the file path cannot be recognized.
name = name.replace('\\', '\\\\').strip()
Read target directory list file
The destination to copy the source file is a group of directories. Similar to the source file list file, I also use a text file to save the absolute paths of multiple directories. The name is "target directory list. lst". As follows:
D:\Catalog 1 D:\Catalog 2 D:\Catalog 3
Define the readdstdirlist function to read the target directory list file, as follows:
def readdstdirlist(filename): if not os.path.isfile(filename): print("Destination directory list file error!") return None try: f = open(filename, 'r') dstlist = f.readlines() n = 0 for name in dstlist: print(name.strip()) name = name.replace('\\', '\\\\').strip() if not os.path.exists(name): print("Target directory%s Can't find!" % name) return None dstlist[n] = name n = n + 1 print("Target directory list contains%s Directories" % len(dstlist)) return dstlist finally: if f: f.close()
Reading the target directory is similar to reading the source file. You also need to escape the backslash, and finally return the absolute path list of the directory.
File copy function
The file copy and copy function requires two parameters: the absolute path list of the source file and the absolute path list of the target directory. It should be noted that before copying, check whether there are files with the same name in the target directory. If there are files, delete them first and then copy them. The functions are as follows:
# Copy the source filegroup to the destination directory def copysrcfiletodstdir(srcfilelist, dstdirlist): if srcfilelist == None: return False if dstdirlist == None: return False filenamelist = [] # Gets the file name of the source file without a path for name in srcfilelist: strs = name.split('\\') filename = strs[-1] filenamelist.append(filename) for dstdirname in dstdirlist: # Check each target directory for active files, and delete if any for filename in filenamelist: fullname = dstdirname + '\\' + filename if os.path.exists(fullname): try: os.remove(fullname) except Exception as e: print("Delete file%s Failed!" % fullname) print("Error:", e) return False # Copy the source file to a destination directory for srcfilename in srcfilelist: print("Copying files%s To directory%s" % (srcfilename, dstdirname)) try: shutil.copy(srcfilename, dstdirname) except Exception as e: print("Copy file%s To directory%s Failed!" % (srcfilename, dstdirname)) print("Error:", e) return False print("All directory files copied successfully!") return True
Finally, it is called in the main function
if __name__ == '__main__': srclist = readsourcelistfile("D:\\source file\\Source file list.lst") dstlist = readdstdirlist("D:\\source file\\Target directory list.lst") copysrcfiletodstdir(srclist, dstlist)
In this way, the whole function is completed. Of course, you can also use tkinter library to add the window interface.
The complete code is as follows:
import os import shutil import sys # Read the source file list and return the file absolute path list def readsourcelistfile(filename): if not os.path.isfile(filename): print("Source file list file error!") return None try: f = open(filename, 'r') srclist = f.readlines() n = 0 for name in srclist: print(name.strip()) name = name.replace('\\', '\\\\').strip() if not os.path.isfile(name): print("source file%s Can't find!" % name) return None srclist[n] = name n = n + 1 print("There are in the source file list%s Files" % len(srclist)) return srclist finally: if f: f.close() # Read the target directory list file and return to the target directory def readdstdirlist(filename): if not os.path.isfile(filename): print("Destination directory list file error!") return None try: f = open(filename, 'r') dstlist = f.readlines() n = 0 for name in dstlist: print(name.strip()) name = name.replace('\\', '\\\\').strip() if not os.path.exists(name): print("Target directory%s Can't find!" % name) return None dstlist[n] = name n = n + 1 print("Target directory list contains%s Directories" % len(dstlist)) return dstlist finally: if f: f.close() # Copy the source filegroup to the destination directory def copysrcfiletodstdir(srcfilelist, dstdirlist): if srcfilelist == None: return False if dstdirlist == None: return False filenamelist = [] # Gets the file name of the source file without a path for name in srcfilelist: strs = name.split('\\') filename = strs[-1] filenamelist.append(filename) # print(filenamelist) for dstdirname in dstdirlist: # Check each target directory for active files, and delete if any for filename in filenamelist: fullname = dstdirname + '\\' + filename if os.path.exists(fullname): try: os.remove(fullname) except Exception as e: print("Delete file%s Failed!" % fullname) print("Error:", e) return False # Copy the source file to a destination directory for srcfilename in srcfilelist: print("Copying files%s To directory%s" % (srcfilename, dstdirname)) try: shutil.copy(srcfilename, dstdirname) except Exception as e: print("Copy file%s To directory%s Failed!" % (srcfilename, dstdirname)) print("Error:", e) return False print("All directory files copied successfully!") return True if __name__ == '__main__': srclist = readsourcelistfile("D:\\source file\\Source file list.lst") dstlist = readdstdirlist("D:\\source file\\Target directory list.lst") copysrcfiletodstdir(srclist, dstlist)