Python batch rename files (picture file as an example)

Rename image files in batch

Using the os package that comes with Python, you can use the **rename()** function to rename the file.

For deep learning materials, picture materials may come from different sources, and their original file names are very different (sometimes the file format is also different).

This article talks about how to rename the image files-combined with **endswith()** to determine the file name, such as ".png", ".jpg", etc. As for the conversion of the image format, you can combine the relevant operations in OpenCV-Python to deal with it yourself to achieve the unity of the file name and file format.

Show me the codes

import os

def renamefiles(pathName):
    i = 0
    for fileName in os.listdir(pathName):# listing all the files in the directory
        # don't rename the unrelated files
        if fileName.endswith('jpg'): # or fileName.endswith('png'):
            #os.path.join: combine the path with file name
            os.rename(os.path.join(pathName,fileName),os.path.join(pathName,(str(i)+'.jpg')))#or .png
        i+=1
    print('Rename finished...')
if __name__=="__main__":
    # current directory
    pathName='./'
    renamefiles(pathName)

Guess you like

Origin blog.csdn.net/weixin_44278406/article/details/108621421