I have a text file which contains the following:
NUM,123
FRUIT
DRINK
FOOD,BACON
CAR
NUM,456
FRUIT
DRINK
FOOD,BURGER
CAR
NUM,789
FRUIT
DRINK
FOOD,SAUSAGE
CAR
I'm trying to change BURGER
but how to do that?
file = open('input.txt', 'r')
while True:
line = file.readline()
if '456' in line:
print line
break
With the above code, I want to pinpoint it using the distinct number after NUM
, but I am only able to read the line where 456
occurs. How to read 3 lines below 456
and then access the BURGER
part?
Thanks!
Update using Levon's solution:
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')
Now how do you write everything back into a new file?