初学python
#初学python:
#1.
##############################
from os.path import walk, join, normpath
import sys
if len(sys.argv) != 2:
print 'input param error, like: add_str filepath'
sys.exit(0)
debug_h='#include \"/dvr/debug/my_debug.h\"\n'
def add_str(file_c):
f = file(file_c)
all = f.readlines()
f.close()
print file_c, '---starting replace...'
all.insert(0,debug_h)
ff = file(file_c, 'w')
for i in range(0, len(all)):
ff.write(all)
ff.close()
print file_c, '---replace over...'
def visit(arg, dirname, names):
files=[normpath(join(dirname, file)) for file in names]
for i in range(0, len(files)):
if files[-2:] in ['.h'] :
add_str(files)
if __name__=="__main__":
path=sys.argv[1]
print 'Starting now...',path
walk(path, visit, 0)
print 'Completed....................'
###############################
#2.
from os.path import walk, join, normpath
import sys
if len(sys.argv) != 4:
print 'input param error, like: replace filepath oldstr newstr'
sys.exit(0)
old_str = sys.argv[2]
new_str = sys.argv[3]
def replace_c(file_c, old, new):
f = file(file_c)
all = f.readlines()
f.close()
print file_c, '---starting replace...'
for i in range(0, len(all)):
all = all.replace(old, new)
ff = file(file_c, 'w')
for i in range(0, len(all)):
ff.write(all)
ff.close()
print file_c, '---replace over...'
def visit(arg, dirname, names):
files=[normpath(join(dirname, file)) for file in names]
for i in range(0, len(files)):
if files[-2:] in ['.c', '.h'] :
replace_c(files, old_str, new_str)
if files[-4:] in ['.cpp', '.txt'] :
replace_c(files, old_str, new_str)
if __name__=="__main__":
path=sys.argv[1]
print 'Starting now...',path
walk(path, visit, 0)
print 'Completed....................'