Skip to content Skip to sidebar Skip to footer

Copy Files To Same Directory With Another Name

I need to copy all html files inside the same directory with another name and I need to navigate all directories inside the source directory. Here is my code so far, import os imp

Solution 1:

Solution

import os
import shutil

def navigate_and_rename(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate_and_rename(s)
        else if s.endswith(".html"):
            shutil.copy(s, os.path.join(src, "newname.html"))    

dir_src = "/home/winpc/test/copy/"
navigate_and_rename(dir_src)

Explanation

Navigate all files in source folder including subfolders

import os
def navigate(src):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            navigate(s)
        else:
            # Do whatever to the file

Copy to the same folder with new name

import shutil
shutil.copy(src_file, dst_file)

Reference

Checkout my answer to another question.


Post a Comment for "Copy Files To Same Directory With Another Name"