Copy files and paste and rename into different folder

Hello All…good day…I am creating a python script to copy files from folder/subfolders into another folder. I did with all success. But I want to rename the copied files into different file name as code. Example, let say i got 3 files copied (file name aa.doc, bb.doc, & cc.doc). After copied I want to save those files into another folder with filenames P001.doc, P002, and P003 respectively. Really need your help. Below is my code.

import os
import shutil

source_folder = r"E:\files\reports\\"
destination_folder = r"E:\files\finalreport\\"

for root, dirs, files in os.walk(source_folder):
    for file in files:
        src_file_path = os.path.join(root, file)
        dst_file_path = os.path.join(destination_folder, file)
        shutil.copy(src_file_path, dst_file_path)

Here is a way to rename the copies:

import os
from pathlib import Path

source_folder = Path("E:/files/reports/")
destination_folder = Path("E:/files/finalreports/")
docno = 0

# Python <3.10
for root, _, files in os.walk(source_folder):
    for file in files:
        docno += 1
        source = Path(root) / file
        target = destination_folder / (f"P{docno:03}" + Path(file).suffix)
        source.link_to(target)

If you are using Python3.10+, use target.hardlink_to(source) instead of source.link_to(target).

In Python3.12+, you will be able to use Path.walk to simplify further:

from pathlib import Path

source_folder = Path("E:/files/reports/")
destination_folder = Path("E:/files/finalreports/")
docno = 0

# Python 3.12+
for root, _, files in source_folder.walk():
    for file in files:
        docno += 1
        source = root / file
        target = destination_folder / (f"P{docno:03}" + file.suffix)
        target.hardlink_to(source)
2 Likes