In our daily life, we often encounter the situation of duplicate files in the computer.

In the case of fewer files, this kind of case is relatively easy to deal with, the worst is a manual comparison delete;

However, when there are many duplicate files, it is difficult to ensure that all duplicate files are deleted.

Here is a handy way to delete duplicate files using Python

Practice time

Python provides an OS module with a built-in computer file management library that you can use to delete unwanted files. When there is a duplicate file name in a document, our system will automatically rename our duplicate file name, such as the following file “1” repeated three times:How do we delete duplicate files from file “1”? Remove (path) function of the OS module can be used to remove the file by specifying the path parameter, that is, the path of the file. I need to remind you that it must be the path that contains the file name. If it is not the path that contains the file name, an error is reported because you are deleting the entire folder.

Code demo

Here we show you the code directly:

Import OS # Load file management library path = "D:\projects" files = os.listdir(path) # os.listdir(path) lists all file names under path and returns them as "list" Print (" path :{} ") print(" path :{} ") print(" path :{} ") Files_delete = files[0:2] files_delete = files[0:2] Print (files_delete) # print(files_delete) File_path = os.path.join(path, file_name) # join(path, file_name) Os. remove(file_path) # delete files print(" Delete duplicate files, what are the names under path :", os.listdir(path)) # print the remaining files after delete duplicate filesCopy the code

Then go to the folder we specified path to look, the duplicate files will be deleted! Function comments in the code:

  1. File_list = os.listdir(path): Lists all files in the specified file path (parameter path) and returns them as a list.
  2. File_path = os.path.join(path, “file name “) : Splices the file path with the file name to form a new path. For example, os.path.join(path=”D: projects”, “xiaobei.txt”) results in “D\projects\xiaobei.txt”\
  3. Os. remove(path) Deletes the file name of the specified path.

conclusion

Use Python to delete duplicate files from your computer.

Of course, it’s important to learn the basics of Python before practicing.