Use Python to rename the files in the folder in order

When processing machine learning pictures, you need to put the pictures into different folders according to the category, and also want to rename the pictures with increments of numbers under the folders to facilitate subsequent processing.
First, let's take a look at the python rename function:
os.rename(src,dst)
src: the name of the directory to be modified
dst: the modified directory name
If dst is an existing directory, OSError will be thrown.
Note: Both src and dst are full path + file name.
First, let's rename the folder
first. Try the simplest method first:

import os
def myrename(path):
    file_list=os.listdir(path)
    i=0
    for fi in file_list:
        old_name=os.path.join(path,fi)
        new_name=os.path.join(path,str(i))
        os.rename(old_name,new_name)
        i+=1

if __name__=="__main__":
    path="D:/test/121"
    myrename(path)

Insert picture description hereWe can see that the folders have been renamed in order, with a slight change, it seems not so low:

import os
def myrename(path):
    file_list=os.listdir(path)
    for i,fi in enumerate(file_list):
        old_name=os.path.join(path,fi)
        new_name=os.path.join(path,"N0."+str(i))
        os.rename(old_name,new_name)

if __name__=="__main__":
    path="D:/test/121"
    myrename(path)

Insert picture description hereThe effect is the same, the role of the enumerate function will not be repeated, we can also use python zip to modify:


import os
def myrename(path):
    file_list=os.listdir(path)
    for i,fi in zip(range(len(file_list)),file_list):
        old_name=os.path.join(path,fi)
        new_name=os.path.join(path,"The."+str(i))
        os.rename(old_name,new_name)


if __name__=="__main__":
    path="D:/test/121"
    myrename(path)

The effect is the same:
Insert picture description hereNext, we rename the file. The above three methods are all available and only need to be changed slightly. I will use the function enumerate as an example to demonstrate:
Insert picture description herefirst create a text document, copy and paste a bunch, as For testing, add a try-except to the function to prevent file renaming errors. Here, the renaming must be a file of the same format, otherwise an error will be reported:

import os
def myrename(path):
    file_list=os.listdir(path)
    for i,fi in enumerate(file_list):
        old_dir=os.path.join(path,fi)
        filename="my"+str(i+1)+"."+str(fi.split(".")[-1])
        new_dir=os.path.join(path,filename)
        try:
            os.rename(old_dir,new_dir)
        except Exception as e:
            print(e)
            print("Failed!")
        else:
            print("SUcess!")

if __name__=="__main__":
    path="D:/test/121"
    myrename(path)

Insert picture description hereThe code is very simple, beginner beginners, here is the simplest method, welcome to exchange and discuss!

Guess you like

Origin blog.csdn.net/liulanba/article/details/110633343