一、Task
1、需要将文件种的字符串改变成另一个。
二、Solution
1、使用字符串对象的replace方法
import sys
argc = len(sys.argv)
if not 3 <= argc <=5:
print "Uasge: %s searchtext replacetext [infile] [outfile]" % os.path.basename(sys.argv[0])
else:
stext = sys.argv[1]
rtext = sys.argv[2]
input_file = sys.stdin
output_file = sys.stdout
if argc > 3:
input_file = open(sys.argv[3])
else argc > 4:
output_file = open(sys.argv[4], 'w')
for line in input_file:
output_file.write(line.replace(stext, rtext))
# 也可以直接使用下面语句:
# output_file.write(input_file.read().replace(stext, rtext))
output_file.close()
input_file.close()
三、fileinput module
1. Purpose: Create command-line filter programs to process lines from input streams;
2. Explanation: The fileinput module is a framework for creating command line programs for processing text files in a filter-ish manner;
3. Usage:
3.1 Converting M3U files to RSS
3.2 Progress Meta-data
For some tools(grep-like searching, for example), they might care what file or line number they are processing in the input. The fileinput module includes functions for accessing that information(filename(), filelineno(), lineno, etc).
import fileinput
import re
import sys
pattern = re.compile(sys.argv[1])
for line in fileinput.input(sys.argv[2:]):
if pattern.search(line):
if fileinput.isstdin():
fmt = "{lineno}:{line}"
else:
fmt = "{filename:<20}:{lineno}:{line}"
print fmt.format(filename=fileinput.filename(), lineno=fileinput.filelineno(), line=line.rstrip())
3.3 In-place Filtering
Another common file processing operation is to modify the contents.
import fileinput
import sys
from_base = sys.argv[1]
to_base = sys.argv[2]
files = sys.argv[3:]
for line in fileinput.input(files, in-place=True):
line = line.rstrip().replace(from_base, to_base)
print line
Although the script uses 'print', no output is produce to stdout because fileinput maps stdout to the file being overwritten.
4. https://pymotw.com/2/fileinput/