Python is really powerful丨Copy the pictures in hundreds of folders to the specified folder in batches, and rename them in order

Recently, I met a friend who asked me how to take out hundreds or thousands of files in batches, put them in a designated folder, and number them in sequence starting from 1.

There are thousands of folders, and there are several pictures in each folder. Good guy, why do I sound familiar, isn’t that what photo albums are like?

But this is not a problem for me. Since there is Python, this is a trivial matter, and it can be done in minutes, but I have to ask him to email me when the time comes!

Saying thousands, the result is only 360 folders in total.

Good boy, it made me happy for nothing!

There are various photos under each folder:

The solution code is as follows:

import os
import shutil

path1 = r"F:\cyclegan\新建文件夹\Dataset_Part1"
pic=os.listdir(path1)
k=0
for i in range(1,len(pic)):
    path="F:/cyclegan/新建文件夹/Dataset_Part1"+"/"+str(i)
    pic2 = os.listdir(path)
    for j in range(1, len(pic2)):
        k=k+1
        shutil.copy(path+"/"+str(j)+".jpg", "F:/cyclegan/新建文件夹/zong" + "/" + str(k) + ".jpg")

For those who are just learning Python, I have packed the learning materials, software tools, e-books, etc. for you, and just grab the business card at the end of the article!

Use two for loops to solve the problem:

1) The os.listdir(path) method is used to return a list of the names of the files or folders contained in the specified folder. Enter print(len(pics)) here to return the number of files in this folder.

2) shutil.copy(path1, path2) copy the file of path1 to path2

3) When writing the path, if there is a circular variable i as the name (such as 1.jpg, 2.jpg...), there must be str in front of i, otherwise an error will be reported (that is, the int type will be converted to str type )

Of course, I also encountered another problem, that is, there are too many photos in a certain folder, and I need to delete some.
For example, select 344 sheets from 2000+ sheets and copy them to another folder.

The code resolves as follows:

import os
import shutil
import random
path1 = r"F:\cyclegan\新建文件夹\zong2"
pic=os.listdir(path1)
j=0
for i in range(1,345):
    number = random.randint(1,len(pic))
    j=j+1
    shutil.copy(path1 + "/" + str(number) + ".jpg", "F:/cyclegan/新建文件夹/testA" + "/" + str(j) + ".jpg")

1) Random numbers are used here for dynamic selection of random. random.randint is used to generate integers

2) shutil.copy is still a copy

Guess you like

Origin blog.csdn.net/fei347795790/article/details/129571931