Home  >  Article  >  Backend Development  >  python批量修改文件后缀示例代码分享

python批量修改文件后缀示例代码分享

WBOY
WBOYOriginal
2016-06-06 11:29:001209browse

ipad的goodreader对JS文件支持不太好,虽然可以读取它但总是无法退出,回不了goodreader的主界面,因此我需要把js文件批量变成纯文本。基于这个目的,我搞了下面一个小应用:

代码如下:


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

import os
def rename():
    path = raw_input("请输入要处理的文件夹路径")
    print path
    old_ext = "."+raw_input("请输入要处理的文件类型")
    print old_ext
    new_ext = "."+raw_input("请输入你想变成的文件类型")
    print new_ext
    for (path, dirs, files) in os.walk(path):#遍历目录树
        for filename in files:
            ext = os.path.splitext(filename)[1] #取得文件类型,注意它还带着点号
            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()

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn