python文件夹同名文件拷贝
请帮我写一个python代码,对比两个文件夹中同名文件,并将同名的文件拷贝到新的文件夹:
import os
import shutil
from pathlib import Path
def copy_same_name_files(folder1_path, folder2_path, output_folder):
# Ensure output folder exists
Path(output_folder).mkdir(parents=True, exist_ok=True)
# Get set of filenames from both folders
folder1_files = set(os.listdir(folder1_path))
folder2_files = set(os.listdir(folder2_path))
# Find common filenames
common_files = folder1_files.intersection(folder2_files)
# Copy common files from folder1 to output folder
copied_count = 0
for file_name in common_files:
source_path = os.path.join(folder1_path, file_name)
dest_path = os.path.join(output_folder, file_name)
# Only copy if it's a file (not a directory)
if os.path.isfile(source_path):
shutil.copy2(source_path, dest_path)
copied_count += 1
print(f"Copied: {file_name}")
print(f"\nCompleted! Copied {copied_count} files to {output_folder}")
# Example usage
if __name__ == "__main__":
folder1 = "path/to/first/folder" # Replace with your first folder path
folder2 = "path/to/second/folder" # Replace with your second folder path
output = "path/to/output/folder" # Replace with your output folder path
copy_same_name_files(folder1, folder2, output)
作者:太一吾鱼水
文章未经说明均属原创,学习笔记可能有大段的引用,一般会注明参考文献。
欢迎大家留言交流,转载请注明出处。
浙公网安备 33010602011771号