[Use python to extract all the files in the folder under the folder and put them in a new folder]

There are multiple files in the file, and there are many photos in jpg format under each file. Extract all the photos and put them in a new folder.

You can use Python's os and shutil libraries to accomplish this task.
For example: There are 95 files under my faces95 folder, and there are 17 to 18 photos under each file.
insert image description here
insert image description here
To extract all the photos, you can use the following python code:

import os
import shutil

# 设置原始文件夹和目标文件夹
data_folder = 'C:\\Users\\ljx\\Desktop\\Images'
photo_folder = 'C:\\Users\\ljx\\Desktop\\new_images'

# 创建目标文件夹
if not os.path.exists(photo_folder):
    os.makedirs(photo_folder)

# 遍历所有文件夹
for root, dirs, files in os.walk(data_folder):
    for file in files:
        # 如果文件是jpg文件
        if file.endswith('.jpg'):
            # 构造原始文件路径和目标文件路径
            src_path = os.path.join(root, file)
            dst_path = os.path.join(photo_folder, file)
            # 复制文件到目标文件夹
            shutil.copyfile(src_path, dst_path)

What needs to be modified: In
insert image description here
data_folder = ' ' , change it to your own file path that needs to be extracted. In photo_folder = ' ' , change it to your own file path that needs to be placed. The default is to create a new file, and you can also create a new one yourself

# 设置原始文件夹和目标文件夹
data_folder = 'C:\\Users\\ljx\\Desktop\\faces95'
photo_folder = 'C:\\Users\\ljx\\Desktop\\new_images'

insert image description here
The running results can be viewed in the specified file path. For example, mine is on the desktop.
insert image description here
If the file is large, the required python running time will be longer, and you need to wait patiently.
If you want to copy other types of files, you can change the condition of the line if file.endswith('.jpg') and you will be fine.

Guess you like

Origin blog.csdn.net/weixin_47869094/article/details/130127868