首页 > 解决方案 > 如何将多个文件复制到另一个目录中?

问题描述

我有一个数据集,包括按升序排列的图像,例如images_0001.pngimages_0002.png...images_0500.png等等。我想将此图像的特定范围复制到另一个目录中。例如,100 张图像将被复制images_0210.pngimages_0310.png. 有人知道该怎么做吗?

标签: pythonpython-3.xfilecopy

解决方案


尝试:

import shutil
import os

start_idx = 210
num_of_files = 100
source_path = "source/path/dir"
dest_path = "dest/path/dir"

for idx in range(start_idx, start_idx + num_of_files):
    src_file_path = os.path.join(source_path, f"images_{idx:04d}.png")
    if os.access(src_file_path, os.R_OK):
        shutil.copy(src_file_path, dest_path)
    else:
        print(f"The file {src_file_path} is not readable")

其中{idx:04d}是文件索引的 4 个字符表示(例如,如果索引为 12,则为 0012)


推荐阅读