python中的文本进程

时间:2012-12-10 12:47:17

标签: python

我有这样的数据:

value1
something text
something text

我想用值改变一些文本。例如:

value1
value1
value1

2 个答案:

答案 0 :(得分:1)

一种方式:

import sys

file = open('file','r')

for line in file:
    if line.startswith('value'):
        pattern=line
    sys.stdout.write(pattern)

将脚本保存到script.py并使用python script.py 运行(其中script为描述性内容)

value1
value1
value1
value2
value2
value3
value3
value3
value3
value3

并重定向输出python script.py > new_file

答案 1 :(得分:1)

with open('input.txt', 'r') as f:
    lines = f.readlines()

value = ''
with open('output.txt', 'w') as f:
    for line in lines:
        if line.startswith('value'):
            value = line
        f.write(value)