python3 achieve folder batch rename picture

Original intention

  1. Exercise Python, improve ability.
  2. Collection of wallpaper folder name life a bit chaotic.
  3. Under can learn some basic libraries

Start (.jpg, no screening)

First

First, find the OS libraries, looking for traversing the file name. Found OS.walk ()

os.walk(top, topdown=Ture, onerror=None, followlinks=False)  
This function can be a triple tupple (dirpath, dirnames, filenames).
dirpath: string, representing the directory path;
dirnames: list, containing the names of all the subdirectories under the current dirpath path (do not include the directory path);
filenames: list, containing the names of all current non-sub-directory under the file dirpath path (do not include the directory path)
Note that, dirnames filenames and exclude path information for a complete path, may be used os.path.join (dirpath, dirnames)

By traversing using os.walk under feelings. Now if only the current directory, then only the first dirpath can be.

Second

Since we need to rename, you need to use os in os.rename (). Because the file name does not contain a file directory, we can merge directory life by os.path.join (), and then rename the cycle to end.

 

But before rename found that the need to bring the full path every time suffix, very inconvenient.

Third

Then a separate file name and extension can be used os.path.splitext (), but think about screening can be separated, PNG classified as a bunch, JPG classified as a pile. Here are jpg, screened in the evening to continue to completion. Jpg put here to rename.

 

Final

Finalization of the code

import the  

def file_name(file_dir):
    dirpath_list=[]
    filenames_list=[]
    old_route=[]
    new_route=[]
    yunying=0
    for dirpath, dirnames, filenames in os.walk(file_dir):
        dirpath_list.append(dirpath)
        filenames_list.append(filenames)
    filenames_list0=filenames_list[0][:]

    for i in filenames_list0:
        old_route.append(os.path.join(dirpath_list[0],i))
        new_route.append(os.path.join(dirpath_list[0],'GuiMie'+str(yunying)+'.jpg'))
        yunying+=1
    try:
        for i in range(len(old_route)):
                os.rename(old_route[i],new_route[i])
        print('rename successfully')
    except Exception as e:
        print(e)

if __name__ == '__main__':
    file_name(r'C:\Users\dell\Pictures\鬼灭')

效果图:

Guess you like

Origin www.cnblogs.com/BOHB-yunying/p/12218614.html