In the process of program development, processing files is a very important part of our daily work. Imagine that when you need to move a bunch of files from one folder to another, manual operations can really make people feel irritated, right? At this time, it is so convenient to use code to deal with these troubles! Today we will talk about how to use Python to quickly copy or cut all files in a file list. Relax and start to do it!
The module we need to use is shutil. This little guy is a very powerful tool in Python. It can help us process files, such as copying, cutting, and deleting files. It has a lot of functions! Next, I will show you the simple example code.
When it comes to copying files, the two functions of shutil.copy2 are always tangled! It will copy the content and permissions of the file. In addition to these, shutil.copy2 will also help you save the file creation time and modification time together. It can be said to be a considerate assistant! To ensure safety, we will use shutil.copy2 here!
Sample code for copying files
OK, let’s take a look at the specific implementation. Suppose we have a list of paths to copy, and our fingers are ready, and we can start!
import shutil import os def copy_files(file_list, destination_folder): if not (destination_folder): (destination_folder) # Create the target folder for file_path in file_list: if (file_path): shutil.copy2(file_path, destination_folder) # Copy the file! print(f"Copyed {file_path} arrive {destination_folder}") else: print(f"{file_path} Not a valid file path。") # Example usagefiles_to_copy = ['/path/to/', '/path/to/', '/path/to/'] dest_folder = '/path/to/destination/' copy_files(files_to_copy, dest_folder)
Does this code look simple? We imported the two good partners: shutil and os, and then check the target folder first, and create it if not! Immediately afterwards, traverse each file path. If the path is valid, start copying, otherwise you will be reminded "Hey, this file path is wrong."
Implementation of cutting files
So, how to cut files? In fact, it is similar to copying, but after copying, you need to delete the original file. Come and take a look at the sample code below!
def move_files(file_list, destination_folder): if not (destination_folder): (destination_folder) # Create the target folder for file_path in file_list: if (file_path): (file_path, destination_folder) # Move the file print(f"Moved {file_path} arrive {destination_folder}") else: print(f"{file_path} Not a valid file path。") # Example usagefiles_to_move = ['/path/to/', '/path/to/'] move_files(files_to_move, dest_folder)
In this code, we use it to move the file, it will automatically help you delete the original file, saving you your worries and effort! You can see that this code is almost exactly the same as the copied ones, only the called functions are different. Isn't it very simple?
Application scenarios of these codes
In actual projects, using Python to process file copying and cutting is a very common scenario, such as data backup, file organization, etc. Sometimes you may be developing a gadget to organize files on your desktop, and these codes can come in handy! Of course, you can further add functions, such as progress bars, error retry, etc., to make the user experience better and smoother.
Oh, by the way, dear programmers, don’t forget to follow a public account called [Programmer Headquarters]! This account was founded by a big boss of Byte. It brings together excellent programmers from major manufacturers such as Alibaba, Byte, Baidu, etc., and shares a lot of practical programming skills and technical updates! If you want to improve your abilities and gain more inspiration, please pay attention!
Let’s do it!
Today we discussed how to easily copy and cut files in Python. This skill helps us save time while also making it easier for us to program. Whether you are a newbie or a veteran with some experience, these little file operation tips can make your code more concise and efficient.
In the world of programmers, practice comes from true knowledge! As long as you are willing to try, everyone will be able to master these basic file operations and become better developers! Let's work hard together and keep moving forward!
Method supplement
9 ways to copy files in Python
Copyfile() method
This method will copy the source content to the destination location only if the target is writable. If you do not have write permissions, an IOError exception will be caused.
It opens the input file for reading and ignores its file type. Next, it won't process special files in any different way, nor will it copy them into new special files.
The Copyfile() method uses the following low-level function copyfileobj(). It takes file names as parameters, opens them and passes the file handle to copyfileobj(). There is an optional third parameter in this method, which you can use to specify the buffer length. It then opens the file and reads the chunk of the specified buffer size. However, the default is to read the entire file at once.
copyfile(source_file, destination_file)
Here are the key points about the copyfile() method.
It copies the source content to the target file.
If the target file is not written, the copy operation will cause an IOError exception.
If the source and target files are the same, it will return a SameFileError.
However, if the target file has a different name before, the copy will overwrite its contents.
If the target is a directory, which means that this method will not be copied to the directory, then Error 13 will occur.
It does not support copying files such as character or block drivers and pipelines.
# Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(()) () print() break else: Continue
Copy() method
copyfile(source_file, [destination_file or dest_dir])
The copy() method functions similar to the "cp" command in Unix. This means that if the target is a folder, then it will create a new file in it that has the same name (base name) as the source file. In addition, this method synchronizes the target file permissions to the source file after copying the contents of the source file.
import os import shutil source = 'current/test/' target = '/prod/new' assert not (source) target = (target, (source)) # create the folders if not already exists (target) # adding exception handling try: (source, target) except IOError as e: print("Unable to copy file. %s" % e) except: print("Unexpected error:", sys.exc_info())
copy() vs copyfile() :
copy() can also set permission bits when copying content, while copyfile() copies only data.
If the target is a directory, copy() will copy the file, and copyfile() will fail with Error 13.
Interestingly, the copyfile() method uses the copyfileobj() method during implementation, while the copy() method uses the copyfile() and copymode() functions in turn.
In Potion-3, it is obvious that copyfile() will be a little faster than copy() because the latter will have an additional task (Permission reserved).
Copyfileobj() method
This method copies the file to the target path or file object. If the target is a file object, then you need to close it after calling copyfileobj() . It also assumes an optional parameter (buffer size) that you can use to set the buffer length. This is the number of bytes saved in memory during copying. The default size used by the system is 16KB.
from shutil import copyfileobj status = False if isinstance(target, string_types): target = open(target, 'wb') status = True try: copyfileobj(, target, buffer_size) finally: if status: ()
Copy2() method
Although the function of the copy2() method is similar to that of copy(). But it can get access and modification times added in the metadata when copying the data. Copying the same file will cause a SameFileError exception.
copy() vs copy2() :
copy() can only set permission bits, while copy2() can also use timestamps to update file metadata.
copy() calls copyfile() and copymode() inside the function, while copy2() calls copystat() to replace copymode().
Popen() method
from shutil import * import os import time from import basename def displayFileStats(filename): file_stats = (basename(filename)) print('\tMode :', file_stats.st_mode) print('\tCreated :', (file_stats.st_ctime)) print('\tAccessed:', (file_stats.st_atime)) print('\tModified:', (file_stats.st_mtime)) ('test') print('SOURCE:') displayFileStats(__file__) copy2(__file__, 'testfile') print('TARGET:') displayFileStats((() + '/test/testfile'))
This method creates a pipeline that sends or accepts commands. It returns an open file object that connects to the pipeline. You can use it for reading or writing based on file opening mode, such as ‘r’ (default) or ‘w’.
(command[, mode[, bufsize]])
mode – it can be 'r' (default) or 'w'
Bufsize – If its value is 0, then there will be no buffering. If it is set to 1, line buffering occurs when accessing the file. If you provide a value greater than 1, buffering will occur when the buffer size is specified. However, for negative values, the system will adopt the default buffer size.
For Windows systems:
import os ('copy ')
For Linux systems:
import os ('cp ')
System() method
This is the most common way to run any system commands. Using the system() method, you can call any command in the subshell. Internally, the method calls the C language standard library functions.
This method returns the exit status of the command.
For Windows systems:
import os ('copy ')
For Linux systems:
import os ('cp ')
7. Copy files using asynchronous thread library
If you want to copy files asynchronously, use the following method. Here, we use Python's thread module to copy operations in the background.
When using this method, make sure to use locking to avoid locking. This may happen if your application uses multiple threads to read/write files.
import shutil from threading import Thread src="" dst="" Thread(target=, args=[src, dst]).start()
8. Copy files using the Call() method of Subprocess
The Subprocess module provides a simple interface to handle child processes. It allows us to start a child process, connect to the child process's input/output/error pipeline, and retrieve the return value.
The subprocess module is designed to replace older modules and functions such as – , *, *, popen2.*
It uses the call() method to call the system command to execute user tasks.
import subprocess src="" dst="" cmd='copy "%s" "%s"' % (src, dst) status = (cmd, shell=True) if status != 0: if status < 0: print("Killed by signal", status) else: print("Command failed with return code - ", status) else: print('Execution of %s passed!\n' % cmd)
9. Use the Check_output() method in subprocess to copy the file
Using the Check_output() method in subprocess, you can run external commands or programs and capture their output. It also supports pipelines.
#No one answers the questions encountered during study? The editor has created a Python learning exchange group: 531509025
#No one answers the questions encountered during study? The editor has created a Python learning exchange group: 531509025 import os, subprocess src=(() + "/") dst=(() + "/") cmd='copy "%s" "%s"' % (src, dst) status = subprocess.check_output(['copy', src, dst], shell=True) print("status: ", ('utf-8'))
This is the article about using Python to quickly copy or cut all files in the file list. For more related Python copy or cut files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!