Python bulk change file suffix sample code sharing

  • 2020-04-02 13:16:58
  • OfStack

The ipad's goodreader doesn't support JS files very well, and although it can be read, it's always impossible to exit and return to the main interface of goodreader, so I need to batch JS files into plain text. For this purpose, I created the following app:


# -*- coding:utf-8 -*-

import os
def rename():
    path = raw_input(" Please enter the folder path to be processed ")
    print path
    old_ext = "."+raw_input(" Please enter the type of file you want to process ")
    print old_ext
    new_ext = "."+raw_input(" Please enter the type of file you want to be ")
    print new_ext
    for (path, dirs, files) in os.walk(path):# Traverse the directory tree 
        for filename in files:
            ext = os.path.splitext(filename)[1] # Gets the file type, notice that it also has a dot 
            print ext;
            if(ext == old_ext):
                print "----------------"
                newname = filename.replace(old_ext, new_ext)
                oldpath = path + "\" + filename
                newpath = path + "\" + newname 
                try:
                    os.rename(oldpath, newpath)
                except BaseException, e:
                   print(str(e))

if __name__ == '__main__':
    rename()


Related articles: