Python功能制作之【遍历某个文件夹,复制某后缀到另一个文件夹中】

在Python中,我们可以使用osshutil模块来轻松地遍历文件夹、复制文件。下面是一个示例代码,展示了如何实现这个功能:

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_dirdestination_dirsource_dir是源文件夹的路径,destination_dir是目标文件夹的路径。

在函数内部,我们首先检查目标文件夹是否存在,如果不存在则创建它。

然后,我们使用os.walk函数遍历源文件夹中的所有文件和子文件夹。

对于每个文件,我们检查其扩展名是否为.png[可以进行更改]

如果是,我们使用shutil.copy2函数将文件复制到目标文件夹中。

最后请确保将source_folderdestination_folder替换为实际的路径。

猜你喜欢

转载自blog.csdn.net/q244645787/article/details/132482613