文章来自《Python cookbook》. 翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!
-- 61.182.251.99 [DateTime(2004-09-20T19:38:11Z)] TableOfContents
描述
文件中查找替换字符串
问题
替换文件中特定字符串
解决
使用string的replace方法可以简单实现字符串替换操作。从指定文件(或标准输入)读入内容,进行处理,然后写入指定文件(或标准输出),工作就完成了。
import os, sys nargs = len(sys.argv) if not 3 <= nargs <= 5: print "usage: %s search_text replace_text [infile [outfile]]" % \ os.path.basename(sys.argv[0]) else: stext = sys.argv[1] rtext = sys.argv[2] input = sys.stdin #标准输入 output = sys.stdout #标准输出 if nargs > 3: input = open(sys.argv[3]) #数据源文件 if nargs > 4: output = open(sys.argv[4], 'w') #数据目的文件 for s in input.xreadlines( ): #读入文件的每一行 output.write(s.replace(stext, rtext)) #处理,并写入目的文件 output.close( ) input.close( )
#译注 : file.xreadlines() is deprecated since Python 2.3, use the following instead
for line in file: process(line)
#end 译注
讨论 Discussion
处理方法很简单,这也是赞的地方。杀鸡不用牛刀。上面的"漂亮"代码是可以执行的脚本。 脚本通过查询参数,确定被替换的字符串,替换字符串,以及输入文件(默认是标准输入), 输出文件(默认是标准输出)。然后循环处理从输入文件读出的每一行,替换字符串,写入输出文件。就这么简单!代码很漂亮,是吧? 还有,脚本最后关闭了两个文件。
As long as it fits comfortably in memory in two copies (one before and one after the replacement, since strings are immutable), we could, with some speed gain, operate on the whole input file's contents at once instead of looping. With today's PCs typically coming with 256 MB of memory, handling files of up to about 100 MB should not be a problem. It suffices to replace the for loop with one single statement:
output.write(input.read( ).replace(stext, rtext))