Copy a batch of files to another folder with python

# 日期:  2023/5/4 11:23
import shutil
import os

# 源文件夹路径
src_folder = 'VOCdevkit/VOC2007/JPEGImages'

# 目标文件夹路径
dst_folder = 'img/0504_test_sets'

# 获取源文件夹中的所有文件
files = os.listdir(src_folder)

lst = []
with open("VOCdevkit/VOC2007/ImageSets/Main/test.txt", "r") as file:
    for line in file:
        img_name = line.strip() + ".jpg"
        lst.append(img_name)

# 遍历文件并逐个复制到目标文件夹
for file_name in files:
    if file_name in lst:
        # 构造源文件路径和目标文件路径
        src_file_path = os.path.join(src_folder, file_name)
        dst_file_path = os.path.join(dst_folder, file_name)
        # 复制文件
        shutil.copy(src_file_path, dst_file_path)

method:

shutil.copy()

The copy() method functions like the "cp" command in Unix. This means that if the destination is a folder, then it will create a new file in it with the same name (basename) as the source file. In addition, this method will synchronize the target file permissions to the source file after copying the content of the source file.

shutil.copyfile():

It copies the source content into the destination file.

If the target file is not writable, the copy operation will raise an IOError exception.

If both the source and destination files are the same, it will return SameFileError.

However, if the destination file previously had a different name, the copy will overwrite its contents.

If the target is a directory, which means this method will not copy to the directory, then Error 13 will occur.

copy() vs copyfile() :

copy() can also set permission bits when copying content, while copyfile() only copies data.

If the target is a directory, copy() will copy the file and copyfile() will fail with Error 13.

Original link: https://blog.csdn.net/ncc1995/article/details/94358099
Reference: [Python] Copy the file to another folder, copy the folder to a new location

Guess you like

Origin blog.csdn.net/ThreeS_tones/article/details/130483817