Python batch changes the method of filename os.rename

  • 2021-01-02 21:55:45
  • OfStack

In our work, we often encounter the operation of renaming large quantities of files, but python provides a very simple method:


import os
 #top It's the target folder ( An absolute path ) . os.walk It reads the files and folders inside until they are empty. 
for a,b,c in os.walk(top='dir'):
 n = len(c)
 # Filter the file size 
 if n >= 10:
 for i in range(n):
  # According to the naming rules for matching segmentation, eg: 4399_0_1234_60.jpg
  name = c[i].split('_',1)[1] # According to the '_' Divided twice ['4399', '0_1234_60.jpg']
  #'$' Define the name you want to add 
  newName = '$' + name
  #os.rename(old_path, new_path)
  #ubuntu The folder path is '/' . Windows Next is '\' . 
  os.rename(a + '/' + c[i],a + '/' + newName)

Related articles: