How can i change file name while copying them using shutil?
Question:
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
Answers:
Shutils supports setting the name of the target file. It mainly depends on how you splice the name of the target file
import shutil
from pathlib import Path
parent_path = Path(__file__).parent
file_path = parent_path.joinpath("test2.py")
shutil.copy(file_path, parent_path.joinpath("test3.py"))
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'
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
Shutils supports setting the name of the target file. It mainly depends on how you splice the name of the target file
import shutil
from pathlib import Path
parent_path = Path(__file__).parent
file_path = parent_path.joinpath("test2.py")
shutil.copy(file_path, parent_path.joinpath("test3.py"))
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'