搜索和替换文件中的文本

一、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/



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值