Akhil
Akhil

Reputation: 49

How to rename a file while copying into another directory in python?

I would like to copy a file from one directory to another with simultaneously renaming the file in python. The "file" need to be copied as "new-file" without renaming the file in source directory. I tried something like this;

     import shutil,os
     src_path="path of source directory"
     dst="path of destination directory"
     for file in os.listdir(src):
         file_path=os.path.join(src_path,file)
          shutil.copy(file_path,dst/"new"+'-'+file)

However this is not working. I know by using os.rename() module, it can be renamed after copying. However i have files with similar names which will be replacing the already copied files in order to avoid which i need to rename each file as "new-file" along with copying itself.

Any help is appreciated. Thanks in advance

Upvotes: 1

Views: 9623

Answers (2)

Ben
Ben

Reputation: 6348

Any time you want to manipulate paths in Python 3, I feel like you should reach for pathlib. Here's a solution that uses shututil's copytree with a custom copy function that uses pathlib. It's nice because it also works with nested directories - note that it doesn't rename directories, only files:

from pathlib import Path
import shutil


def copy_and_rename(src: str, dst: str):
    """copy and rename a file as new-<name>"""
    new_name = "new-" + Path(dst).name
    new_dst = Path(dst).with_name(new_name)
    shutil.copy2(src, new_dst)


shutil.copytree(
    "./copy-from-me", "./copy-to-me", copy_function=copy_and_rename, dirs_exist_ok=True
)

Here's an example of running this:

$ tree copy-from-me
copy-from-me
├── 1.txt
├── 2.txt
└── nested
    └── 3.txt

$ tree copy-to-me
copy-to-me
├── nested
│   └── new-3.txt
├── new-1.txt
└── new-2.txt

Upvotes: 2

alani
alani

Reputation: 13079

Your attempt to join strings together using dst/"new" will not work because this is attempting to perform a division. You have correctly used os.path.join when creating the full path for the source file, and you simply need to do the same thing with the destination file also.

import shutil
import os

src_path = "path of source directory"
dst = "path of destination directory"

for file in os.listdir(src_path):
    file_path = os.path.join(src_path, file)
    shutil.copy(file_path, os.path.join(dst, "new-" + file))

Upvotes: 2

Related Questions