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)
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 .
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.
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.
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)
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
import shutil
shutil.copy(src_file, dst_file)
Checkout my answer to another question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With