在 Python 中复制文件夹并重命名文件扩展名
此脚本递归地将 myfolder 复制到 myfolder2 并将所有 .txt 文件重命名为 .xml
copy_and_rename_extensions.py
#!/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:
# 将 .txt 重命名为 .xml
if file.endswith(".txt"):
dstfile_name = re.sub(r"\.txt$", ".xml", file) # 正则表达式仅替换字符串末尾的 .txt
else:
dstfile_name = file
# 计算目标路径
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)
# 如果目录不存在则创建
os.makedirs(os.path.dirname(dstpath), exist_ok=True)
# 复制文件(copy2 保留元数据)
shutil.copy2(srcpath, dstpath)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow