在Python中,我们可以使用os
和shutil
模块来轻松地遍历文件夹、复制文件。下面是一个示例代码,展示了如何实现这个功能:
import os
import shutil
def copy_png_files(source_dir, destination_dir):
# 创建目标文件夹(如果不存在)
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
# 遍历源文件夹中的所有文件和子文件夹
for root, dirs, files in os.walk(source_dir):
for file in files:
# 如果文件扩展名是.png,复制到目标文件夹中
if file.endswith('.png'):
source_path = os.path.join(root, file)
destination_path = os.path.join(destination_dir, file)
shutil.copy2(source_path, destination_path)
# 指定源文件夹的路径
source_folder = 'path'
# 指定目标文件夹的路径
destination_folder = 'path'
copy_png_files(source_folder, destination_folder)
这个函数copy_png_files
接收两个参数:source_dir
和destination_dir
。source_dir
是源文件夹的路径,destination_dir
是目标文件夹的路径。
在函数内部,我们首先检查目标文件夹是否存在,如果不存在则创建它。
然后,我们使用os.walk
函数遍历源文件夹中的所有文件和子文件夹。
对于每个文件,我们检查其扩展名是否为.png[可以进行更改]
。
如果是,我们使用shutil.copy2
函数将文件复制到目标文件夹中。
最后请确保将source_folder
和destination_folder
替换为实际的路径。