python 如何将照片从源文件夹提取到目标文件夹?

6uxekuva  于 2023-04-19  发布在  Python
关注(0)|答案(1)|浏览(143)

我需要创建一个程序,只从预定的源文件夹中提取照片,其中包含许多子文件夹(和文件类型),并将图像放入预定的目标文件夹及其子文件夹中。
代码只适用于第一个文件夹,我不知道如何使其工作的休息。
源文件夹中每个子文件夹的内容类似:不同文件类型的组合。
所附的图像显示了我试图实现的功能:
enter image description here
下面的代码是我所做的。同样,它可以工作,但只适用于第一个文件夹。

import os
import shutil

# set source directory
source_dir = r"C:\Users\YourUserName\SourceDirectory"

# set destination directory
destination_dir = r"C:\Users\YourUserName\DestinationDirectory"

# set file extension to filter for
file_extension = ".jpg", ".jpeg", ".png"

# iterate through folders in source directory
for foldername in os.listdir(source_dir):
    folder_path = os.path.join(source_dir, foldername)
    
    # check if current path is a directory
    if os.path.isdir(folder_path):
        # iterate over files in current directory
        for file in os.listdir(folder_path):
            # check if file has the desired extension
            if file.endswith(file_extension):
                # construct full path for source file and destination file
                source_file_path = os.path.join(folder_path, file)
                destination_file_path = os.path.join(destination_dir, foldername, file)

                # create directory in destination directory if it doesn't exist
                os.makedirs(os.path.dirname(destination_file_path), exist_ok=True)

                # copy file to destination directory
                shutil.copy(source_file_path, destination_file_path)
                print(f"Copied {source_file_path} to {destination_file_path}")
sqougxex

sqougxex1#

要在文件夹和子文件夹之间巡回,可以使用os.walk

for root, dirs, files in os.walk(source_dir):
    for name in files:
        if name.endswith(file_extension):

            # construct full path for source file and destination file
            filepath = subdir + os.sep + file

            destination_file_path = destination_dir + os.sep + dirs + os.sep + file

            # create directory in destination directory if it doesn't exist
            os.makedirs(os.path.dirname(destination_file_path), exist_ok=True)

            # copy file to destination directory
            shutil.copy2(source_file_path, destination_file_path)
            print(f"Copied {source_file_path} to {destination_file_path}")

您也可以使用它将完整路径保存到自定义列表中:

  • (从这里出发)*
imagefiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(source_dir)
             for name in files
             if name.endswith(file_extension)]

相关问题