Search code examples
pythonshutil

How can i change file name while copying them using shutil?


I am using shutil to copy my files to another destination directory , what i want to achieve is

src/red.png
src/blue.png
src/green.png

for example if i select blue and green then while saving i want them to be saved as

dst/blue_1001.png
dst/green_1002.png

Thanks

Kartikey


Solution

  • All you need to do is to construct a destination path in a format that you want and shutil will do rest of the job.

    I am using pathlib module here because it provides convenient APIs to work with paths.

    >>> import shutil
    >>> from pathlib import Path
    >>> 
    >>> files_to_copy = ["src/red.png", "src/blue.png"]
    >>> 
    >>> destination = Path("dst")
    >>> 
    >>> for index, file in enumerate(map(Path, files_to_copy), start=1001):
    ...     destination_filename = f"{file.stem}_{index}{file.suffix}"
    ...     print(f"{destination_filename=}")
    ...     _ = shutil.copy(file, destination / destination_filename)
    ... 
    destination_filename='red_1001.png'
    destination_filename='blue_1002.png'