修改文本文件中的word

实验室干活儿,突然有需求,要修改一个文件夹下N个文件(我也不知道有多少个,木有数过)中的同一个word,so,写了一个这个玩意儿。。。欢迎讨论和拍砖!发现自己要多看看Python的doc了。。。
#! /usr/bin/env python

#
# This is .py file for modifying words in a directory
#
# Author: luotuo
# Date: 2012.12.26
#

import os
import sys

def print_usage():
    print "The Usage:"
    print "./modify_words argv1 argv2 argv3"
    print "Here, argv1 is the directory or file you want to modify"
    print "argv2 is the word you want to modify"
    print "argv3 is the new word you want to use"
    
def traversal_dir(dir, old_word, new_word):
    dir_list = os.listdir(dir)
    for l in dir_list:
        if os.path.isfile(os.path.join(dir, l)):
            # Open it and replace
            path = os.path.join(dir, l)
            replace_word(path, old_word, new_word)
        else:
            path = os.path.join(dir, l)
            traversal_dir(path, old_word, new_word)

def replace_word(file, old_word, new_word):
    try:
        f = open(file, 'r')
        path = os.path.dirname(file)
        filename = "/temp_" + os.path.basename(file)
        filename = path + filename
        f_temp = open(filename, 'w')
        # FIXME: It can be optimized later
        for line in f.readlines():
            line = line.replace(old_word, new_word)
            if line:
                f_temp.write(line)
        f.close()
        name = "/" + os.path.basename(file)
        os.remove(file)
        f_temp.close()
        os.rename(filename, path+name)
    except:
        print "There is something wrong!"

def main(argv):
    # check sys.argv
    # argv[0]: directory or file
    # argv[1]: old words
    # argv[2]: new words
    if len(argv) != 3:
        print "The arguments are wrong!"
        print_usage()
        sys.exit(1)
    else:
        # handle it
        dest = argv[0]
        old_word = argv[1]
        new_word = argv[2]
        # check if the argv[0] is a directory or not
        if os.path.isdir(dest):
            # Traversal the directory
            traversal_dir(dest, old_word, new_word)
        else:
            # check if the argv[0] is a file or not
            if os.path.isfile(dest):
                # Open it and replace the word
                replace_word(dest, old_word, new_word)
            else:
                print_usage()
                sys.exit(1)

if __name__ == '__main__':
    main(sys.argv[1:])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值