替换文本文件中的单词并将其写入python中的新文件

时间:2012-08-22 23:11:48

标签: python text line

所以我有一个包含以下内容的文本文件:

NUM,123
FRUIT
DRINK
FOOD,BACON
CAR
NUM,456
FRUIT
DRINK
FOOD,BURGER
CAR
NUM,789
FRUIT
DRINK
FOOD,SAUSAGE
CAR

我将“BURGER”改为“PIZZA”

with open('input.txt','r') as f:
    data = f.readlines()
    for i, line in enumerate(data):
        if '456' in line:
            field = ','.join(data[i+3].split(',')[1])
            field = field.replace(field,'PIZZA')

如何将所有内容写回新文件,以便在新文件中将其写入:

NUM,123
FRUIT
DRINK
FOOD,BACON
CAR
NUM,456
FRUIT
DRINK
FOOD,PIZZA
CAR
NUM,789
FRUIT
DRINK
FOOD,SAUSAGE
CAR

谢谢!

5 个答案:

答案 0 :(得分:2)

你非常接近,请尝试以下方法:

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

with open('output.txt','w') as f:
    for i, line in enumerate(data):
        if '456' in line:
            fields = data[i+3].split(',')
            fields[-1] = 'PIZZA\n'
            data[i+3] = ','.join(fields)
        f.write(line)

答案 1 :(得分:2)

这适用于您已有的代码。它只是添加一行来更新您的数据,然后添加代码将其全部写入文件:

# read the data
with open('data.txt') as f:
    data = f.readlines()

# process data
for i, line in enumerate(data):
    if "456" in line:
        field = ','.join(data[i+3].split(',')[1])
        field = field.replace(field,'PIZZA')
        data[i+3] = '{},{}\n'.format(data[i+3].split(',')[0],field) # added 

# write data to file
with open('result.txt', 'w') as outfp: # to write out data 
    outfp.write(''.join(data))

答案 2 :(得分:0)

以附加模式打开文件并替换单词。

答案 3 :(得分:0)

这个解决方案更安全一点,因为如果'456'行之后的字段少于三个,它就不会中断。它还避免了创建中间列表,只是将每个输入行直接写入输出文件。

with open('output.txt', 'w') as outfile:
    with open('input.txt', 'r') as infile:
        index = -1
        for line in infile:
            if index >= 0:
                index += 1
                if index == 3:
                    line = '%s,PIZZA\n' % line.rstrip().split(',')[0]
                    index = -1
            elif '456' in line:
                index = 0
            outfile.write(line)

答案 4 :(得分:0)

好吧,如果你只是用另一个字符串替换另一个字符串,为什么要逐行处理?这样的事情应该有效:

with open('input.txt', 'r') as f:
    with open('output.txt', 'w') as target:
        target.write(f.readline().replace("BURGER","PIZZA"))