Jan-20-2023, 10:32 PM
What do you mean by duplicate files? If you mean files with the same name, that is impossible. File names in a folder have to be unique. When you move a file with a name that matches a file in the target folder, the file in the target folder is replaced.
To allow moving "duplicate" files, you'll need to rename files that are duplicates. Before calling move, check if the filename is already used in the target folder. If it is, modify the filename with a version string or a date/timestamp.
This code appends a version to the filename.
To allow moving "duplicate" files, you'll need to rename files that are duplicates. Before calling move, check if the filename is already used in the target folder. If it is, modify the filename with a version string or a date/timestamp.
This code appends a version to the filename.
import glob import os import shutil from pathlib import Path SOURCE_PATH = Path(move files from here) TARGET_PATH = Path(move files to here) for m in ("123", "456", "789"): # didn't want to make a csv file of phone numbers for source in glob.glob(os.path.join(SOURCE_PATH, f"*{m}*")): filename = Path(source).name version = 1 while True: target = TARGET_PATH / filename if target.exists(): # is a duplicate filename, make a unique filename filename = Path(source).name stem, ext = filename.split(".", maxsplit=1) # Will crash if no extension. Exercise left to the reader filename = f"{stem}_V{version}.{ext}" version += 1 else: break shutil.move(source, TARGET_PATH / filename)