- 1 year ago
Automatically renaming duplicate files in folder with incremental numbers
Comment
1 / 1
To automatically rename duplicate files in a folder with incremental numbers, you can use the following Python code:
pythonimport os
def rename_duplicates(folder_path):
file_counts = {}
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
# Get the base filename without extension
file_name, file_extension = os.path.splitext(filename)
# Check if the base filename already exists
if file_name in file_counts:
file_counts[file_name] += 1
new_file_name = f"{file_name}_{file_counts[file_name]}{file_extension}"
else:
file_counts[file_name] = 0
new_file_name = filename
new_file_path = os.path.join(folder_path, new_file_name)
os.rename(file_path, new_file_path)
print(f"Renamed {file_path} to {new_file_path}")
# Specify the folder path where you want to rename duplicate files
folder_path = "/path/to/folder"
rename_duplicates(folder_path)
Here's how the code works:
- The
rename_duplicates
function takes thefolder_path
as an argument. - It initializes a dictionary called
file_counts
to keep track of the number of occurrences for each base filename. - It loops through each file in the specified folder using
os.listdir
. - For each file, it checks if it is a regular file using
os.path.isfile
. - It splits the filename into the base filename and extension using
os.path.splitext
. - If the base filename already exists in the
file_counts
dictionary, it increments the count and constructs a new filename by appending the count and extension. - If the base filename is encountered for the first time, it initializes the count to 0 and keeps the original filename.
- It constructs the new file path by joining the folder path and the new filename using
os.path.join
. - It renames the file using
os.rename
by providing the original file path and the new file path. - Finally, it prints a message indicating the renaming operation.
Make sure to replace /path/to/folder
with the actual path to the folder where you want to rename the duplicate files.