In the life , We often encounter duplicate files in the computer .
In the case of fewer files , This kind of situation is relatively easy to handle , The worst thing is to manually compare and delete one by one ;
And when there are many duplicate files , It is difficult for us to guarantee that all duplicate documents will be deleted .
Leader Huang here has brought us a convenient method —— use Python To remove duplicate files
Practice time
Python Provide a built-in computer file management library os modular , We can use it to delete superfluous files .
When there are duplicate file names in a document , Our system will automatically rename our duplicate file names , For example, the following file “1” repeated 3 Time :
So how do we delete files “1” What about duplicate files ?
We can use os Modular os.remove(path) function , Just specify path Parameters , That is, the path of the file , You can delete the file .
I need to remind you that , It must be the path containing the file name .
If it is not the path containing the file name , You're going to report a mistake , Because this is deleting the entire folder .
Code demonstration
Here we show you the code directly :
import os # Load file management library path = "D:\projects" files = os.listdir(path) # os.listdir(path) List path The names of all files under the are combined with ” list “ Form return of print(type(files)) # verification files The type of print(" route :{} The files owned under are {}".format(path, files)) # Print path All file names under files_delete = files[0:2] # Find the file name you want to delete , Here we can also use input Function to specify the file I need to delete ! print(files_delete) # Print the file name to delete for file_name in files_delete: file_path = os.path.join(path, file_name) # Application os.path.join(path, file_name) Concatenate file path and file name , Form a new path os.remove(file_path) # Delete file print(" After deleting duplicate files , path What are the file names under :", os.listdir(path)) # Print the remaining files after deleting duplicate files
Then go to the folder of the path we specified , Duplicate files are deleted !
Function annotations in code :
summary
Students can try it on their own Python Remove duplicate files from your computer !
Of course , Before practice , Study Python The basic knowledge of is very important .