During the daily file management and processing process, we may encounter the need to organize files into different folders. For example, we have a directory with multiple files, and the first character of the file name indicates which folder the file should be stored. We can use Python scripts to automatically complete this task and implement file classification and sorting. This article will introduce how to write a script in Python to implement the following functions:
Check and delete empty folders
Classify the file by the first character of the file name and move it to the corresponding folder.
1. Basic Requirements
Suppose we have a folder save with multiple files and some empty folders. We need to do the following:
Delete an empty folder: First check whether the folder is empty. If it is an empty folder, delete it.
Move the file to the corresponding folder: Move the file to the corresponding folder according to the first letter of the file name.
2. Implement code parsing
import os import shutil # Set the file save pathsave_path = './save' # traverse all files and folders in the directoryfor file in (save_path): # If it is a folder if ((save_path, file)): try: # Try to delete an empty folder ((save_path, file)) print('Delete empty folder:', file) except Exception as e: # If the folder is not empty, catch the exception and output the error message print('>>>', e) continue # Get the initial letter of the file name file_dir = (save_path, file[0]) # If the target folder does not exist, create it if not (file_dir): (file_dir) # Move the file to the corresponding folder ((save_path, file), (file_dir, file))
3. Code explanation
3.1 (save_path)
(save_path) lists all files and folder names under the save folder. The returned content is a list containing file names (including folders and files).
3.2 Delete empty folders
if ((save_path, file)): try: ((save_path, file)) print('Delete empty folder:', file) except Exception as e: print('>>>', e) continue
: Check whether the specified path is a folder.
: Delete empty folder. If the folder is not empty, deletion will fail and an exception is thrown. We use try-except to catch the exception and output the error message.
If the item is an empty folder, print the prompt message and skip the folder to continue processing other files.
3.3 Classify and move files according to the initial letter of the file
file_dir = (save_path, file[0]) if not (file_dir): (file_dir) ((save_path, file), (file_dir, file))
file[0]: Get the first letter of the file name, which determines which folder the file should be classified into.
(file_dir): Check whether the target folder exists. If it does not exist, create a new folder using it.
: Move the file from the source path to the destination path.
4. Code execution results
After running this script, the system will traverse all files in the save directory and perform the following operations:
Delete all empty folders.
Create a new folder based on the initial letter of each file name and move the file to the corresponding folder.
For example, suppose there is the following file in the save folder:
Empty folder1
After executing the script, there will be three new folders in the save directory:
a/, including
b/, including
c/, including
The empty folder folder1 will be deleted.
5. Summary
This Python code implements automated file classification and empty folder deletion through the os and shutil modules. Such scripts are very useful in scenarios such as file organization and data cleaning. You can modify folder classification rules according to actual needs, such as using file extensions, file sizes, etc. as classification standards.
Method supplement
One –> Many
The code is as follows, convenient for backup:
import shutil import os def remove_file(old_path, new_path): print(old_path) print(new_path) filelist = (old_path) # List all files in this directory. The file list returned by listdir does not contain paths. # print(filelist) for i, file in enumerate(filelist): src = (old_path, file) dst = (new_path, file) # print('src:', src) # print('dst:', dst) (src, dst) # If it is copying, change it to the following code # (src, dst) # Split quantity if (i == 999): break if __name__ == '__main__': for i in range(1, 12): name = 'Create a new folder' + str(i) if (name)==False: (name) remove_file(r"F:\Picture Name\Picture", name)
More –> One
import shutil import os def remove_file(old_path, new_path): print(old_path) print(new_path) filelist = (old_path) # List all files in this directory. The file list returned by listdir does not contain paths. # print(filelist) for i, file in enumerate(filelist): src = (old_path, file) dst = (new_path, file) # print('src:', src) # print('dst:', dst) (src, dst) # If it is copying, change it to the following code # (src, dst) if __name__ == '__main__': for i in range(1, 12): name = 'Create a new folder' + str(i) remove_file(name, r"E:\Server Data\test_latest\11068")
This is the article about renaming files in Python and moving them to the corresponding folder. For more related contents of Python renaming files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!