实验室干活儿,突然有需求,要修改一个文件夹下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:])