如何用Python复制文件到多文件夹并修改文件内指定变量值
解决方案
你的代码仅完成了文件复制操作,未实现内容修改需求。以下是两种可行的实现方案:
方法1:读取原内容后直接生成修改后的目标文件
无需先复制再修改,直接读取原文件内容并修改后写入目标文件夹,效率更高:
import os import re # 配置路径与目标编号 src_path = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\Test.py" target_folders = [1, 2] # 读取原文件内容 with open(src_path, 'r', encoding='utf-8') as f: original_content = f.read() for folder_num in target_folders: # 构造目标文件夹与文件路径 dst_folder = rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\{folder_num}" dst_file_path = os.path.join(dst_folder, "Test.py") # 自动创建不存在的目标文件夹 os.makedirs(dst_folder, exist_ok=True) # 修改内容:替换File=后的数字为当前文件夹编号 modified_content = re.sub(r'File=\d+', f'File={folder_num}', original_content) # 写入修改后的内容 with open(dst_file_path, 'w', encoding='utf-8') as f: f.write(modified_content) print(f"完成:文件夹{folder_num}的Test.py已生成")
方法2:先复制文件,再修改目标文件内容
如果需要保留"先复制再修改"的逻辑,可使用以下代码:
import shutil import os import re src_path = r"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\Test.py" target_folders = [1, 2] for folder_num in target_folders: dst_folder = rf"C:\Users\USER\OneDrive - Technion\Research_Technion\Python_PNM\Surfactant A-D\Multiple copy pasting\{folder_num}" dst_file_path = os.path.join(dst_folder, "Test.py") # 确保目标文件夹存在 os.makedirs(dst_folder, exist_ok=True) # 复制原文件到目标位置 shutil.copy(src_path, dst_file_path) # 读取并修改目标文件内容 with open(dst_file_path, 'r', encoding='utf-8') as f: content = f.read() modified_content = re.sub(r'File=\d+', f'File={folder_num}', content) # 写回修改后的内容 with open(dst_file_path, 'w', encoding='utf-8') as f: f.write(modified_content) print(f"完成:文件夹{folder_num}的Test.py已复制并修改")
关键细节说明
os.makedirs(dst_folder, exist_ok=True):避免因目标文件夹不存在导致报错,自动创建文件夹- 正则表达式
re.sub(r'File=\d+', ...):适配原文件中File=后为任意数字的情况,比固定替换File=1更通用 - 指定
encoding='utf-8':避免不同操作系统下的文件编码问题
内容的提问来源于stack exchange,提问作者KeplerNick123
相关产品推荐
相关产品推荐

