Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
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)
like image 683
Kit Avatar asked Jul 07 '17 15:07

Kit


People also ask

How do you create a copy of a file in the same directory?

To create a copy of a file in the same folder, overwriting existing files. Use the CopyFile method, supplying the target file and location, and setting overwrite to True .

How do you make a copy of a file with a different name in Linux?

By Using cp Command Linux system users can copy folders, directories, and files using the cp command. We can use cp commands along with destination and source only. Here along with the file's path, the filename is also changed—the syntax for the cp command.

How do I copy and rename multiple files in Linux?

If you want to rename multiple files when you copy them, the easiest way is to write a script to do it. Then edit mycp.sh with your preferred text editor and change newfile on each cp command line to whatever you want to rename that copied file to.


1 Answers

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.

like image 151
YLJ Avatar answered Oct 28 '22 23:10

YLJ