当前位置:编程学习 > 网站相关 >>

修改文件名中的字段

突然发现,之前那个文件夹中的文件名也是要修改的。。。so,又写了一个脚本。欢迎拍砖讨论!
[python]  
#! /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 sys  
import os  
  
def 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   www.zzzyk.com
        #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:])  
 
补充:Web开发 , Python ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,