Coyping a folder and renaming file extensions in Python
This script copies myfolder
to myfolder2
recursively and renames all .txt
files to .xml
#!/usr/bin/env python3
import os
import os.path
import re
import shutil
srcfolder = "myfolder"
dstfolder = "myfolder2"
for subdir, dirs, files in os.walk(srcfolder):
for file in files:
# Rename .txt to .xml
if file.endswith(".txt"):
dstfile_name = re.sub(r"\.txt$", ".xml", file) # Regex to replace .txt only at the end of the string
else:
dstfile_name = file
# Compute destination path
srcpath = os.path.join(subdir, file)
dstpath_relative_to_outdir = os.path.relpath(os.path.join(subdir, dstfile_name), start=srcfolder)
dstpath = os.path.join(dstfolder, dstpath_relative_to_outdir)
# Create directory if not exists
os.makedirs(os.path.dirname(dstpath), exist_ok=True)
# Copy file (copy2 preserves metadata)
shutil.copy2(srcpath, dstpath)