以下是一个遍历复制和文本的示例解决方法:
import os
import shutil
# 定义源文件夹路径和目标文件夹路径
source_folder = 'path/to/source/folder'
target_folder = 'path/to/target/folder'
# 遍历源文件夹中的所有文件和子文件夹
for root, dirs, files in os.walk(source_folder):
# 构建目标文件夹的对应子文件夹路径
target_root = os.path.join(target_folder, os.path.relpath(root, source_folder))
# 创建目标文件夹
os.makedirs(target_root, exist_ok=True)
# 遍历源文件夹中的文件
for file in files:
# 构建源文件路径和目标文件路径
source_file = os.path.join(root, file)
target_file = os.path.join(target_root, file)
# 复制文件
shutil.copy2(source_file, target_file)
# 遍历复制完成后,可以进行其他文本处理
# 例如,打开目标文件夹中的所有txt文件,并在每个文件开头添加一行文本
for root, dirs, files in os.walk(target_folder):
for file in files:
if file.endswith('.txt'):
file_path = os.path.join(root, file)
with open(file_path, 'r+') as f:
content = f.read()
f.seek(0, 0) # 将文件指针移到开头
f.write('Added text\n' + content)
请注意,上述代码是使用Python语言编写的示例,并假设源文件夹中只包含文件(没有子文件夹)。在实际应用中,您可能需要根据自己的需求进行适当的修改和调整。