所以我有一个包含以下内容的文本文件:
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
谢谢!