1

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

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

我用“PIZZA”代替“BURGER”这个词

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

谢谢!

4

5 回答 5

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)
于 2012-08-22T23:21:07.647 回答
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))
于 2012-08-22T23:23:22.827 回答
0

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

于 2012-08-22T23:16:55.367 回答
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)
于 2012-08-23T02:06:44.633 回答
0

好吧,如果您只是用另一个字符串替换一个字符串,为什么要逐行处理?像这样的东西应该工作:

with open('input.txt', 'r') as f:
    with open('output.txt', 'w') as target:
        target.write(f.readline().replace("BURGER","PIZZA"))
于 2012-08-23T09:22:47.957 回答