Python batch modification of file suffixes

  • 2020-04-02 13:25:34
  • OfStack

Recently downloaded a lot of various tutorials, but unfortunately is the suffix name is ".mp4", and I like ".rmvb" suffix, because there is a slight cleanliness, can't stand the ".mp4" fix, but manual modification is too tedious, so use recently just learned Python to lazy!     :)

The figure is the file name before the program runs

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/2014126160545696.jpg" >

All we need to do is create a new python file in the current directory, like demo2.py above, and then open it with the editor and type in the following code:


import os
#  Lists all files in the current directory 
files = os.listdir(".")       
for filename in files:
    portion = os.path.splitext(filename)
    #  If the suffix is .txt
    if portion[1] == ".mp4":  
        #  Recombine the filename and suffix    
        newname = portion[0] + ".rmvb"   
        os.rename(filename,newname)

Okay, save and run your program after you've written it!

Not surprisingly, you'll be surprised to find:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201401/2014126160709190.jpg" >

Haha, all files with ".mp4" suffix should be ".rmvb" suffix!!    


Related articles: