修改文件名中的字段

来源:互联网 发布:黑色沙漠捏脸数据放哪 编辑:程序博客网 时间:2024/06/08 11:41

突然发现,之前那个文件夹中的文件名也是要修改的。。。so,又写了一个脚本。欢迎拍砖讨论!微笑

#! /usr/bin/env python## This is a .py file to replace a letter or a word with the letter# or the word provided## Author: luotuo# Date: 2012.12.26#import sysimport osdef usage():    print "Usage:"    print "./rename argv[1] argv[2] argv[3]"    print "Here, argv[1] is the dirctory you choose"    print "argv[2] is the letter or word you want to replace"    print "argv[3] is the letter or word you want to use"    def traversal_dir(dir, old_word, new_word):    list_dir = os.listdir(dir)    for l in list_dir:        if os.path.isfile(os.path.join(dir, l)):            rename(os.path.join(dir, l), old_word, new_word)        else:            path = os.path.join(dir, l)            traversal_dir(path, old_word, new_word)            def rename(filename, old_word, new_word):    if os.path.basename(filename).find(old_word) == -1:        return    else:        name = os.path.basename(filename)        name = name.replace(old_word, new_word)        name = "/" + name        #print os.path.dirname(filename)        full_name = os.path.dirname(filename) + name        #print full_name        os.rename(filename, full_name)def main(argv):    if len(argv) != 3:        print "Please see the Usage"        usage()    else:        old_word = argv[1]        new_word = argv[2]        if os.path.isfile(argv[0]):            rename(argv[0], old_word, new_word)        else:            # argv[0] is a directory            dir = argv[0]            # traversal it            traversal_dir(dir, old_word, new_word)if __name__ == '__main__':    main(sys.argv[1:])