15

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
import shutil
os.chdir('/') 

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

for filename in os.listdir(dir_src):
    if filename.endswith('.html'):
        shutil.copy( dir_src + filename, dir_src)
    print(filename)
3
  • So basically renaming each file? os.rename and glob might help
    – Taku
    Commented Jul 7, 2017 at 15:48
  • Actually i do not need to rename.I need to remain original file as it is.I need to get a copy to same folder with another name
    – Kit
    Commented Jul 7, 2017 at 15:55
  • Why not issue a shell command? The find and copy functions all have recursive switches that will alleviate the problem.
    – Prune
    Commented Jul 7, 2017 at 16:30

1 Answer 1

17

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.

1
  • I found shutil is very useful.
    – Evan Hu
    Commented Dec 29, 2018 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.