I am quite beginner to python and trying to make a script that stores value inside the if statement. I've browsed many questions here but sadly, None of those clearly solved my problem yet.
What I want to do is to mark numbers below the line that contains only the word 'orange'.
Here is my simple code that I've tried so far:
with open("input.txt", "r") as inp:
with open("output.txt", "w") as oup:
for line in inp.readlines():
# while True:
number = 0
if "orange" in line:
number =1
print(number)
oup.write(line)
That is, I want to make the input.txt into desired output.txt as below:
input.txt
...
some random texts
...
grape sldkfjasldkalg
lsadkgjag orange
apple
alsdfkjalkdfjalfkdlsf orange
banana
orange sldsjkd
orange asskdjhgskg
cucumber
...
some random texts
...
output.txt
...
some random texts
...
grape sldkfjasldkalg
lsadkgjag orange
0
apple
alsdfkjalkdfjalfkdlsf orange
1
banana
orange sldsjkd
2
orange asskdjhgskg
3
cucumber
...
some random texts
...
However When I run that code, the number stops at '1'and doesn't increment at all.
That's why I want to know the way to store values and increment it inside if-statement. and I want to solve it by just modifying my orignal code that uses readlines()
Can anyone give me any guidelines to solve this? thanks.
CodePudding user response:
Every time you do the for loop, you set the value number = 0
That's why the increment doesn't work.
You should initiate the number before the for statement:
with open("input.txt", "r") as inp:
with open("output.txt", "w") as oup:
number = 0
for line in inp.readlines():
if "orange" in line:
number =1
print(number)
oup.write(line)
CodePudding user response:
The variable number=0
has to be initialized before the loop.
You also have to write the number to the file. It is missing in your code. For writing to the text file, it is simpler to use the print
function and specify the parameter file
.
number = 0
with open("input.txt", "r") as inp:
with open("output.txt", "w") as oup:
for line in inp:
print(line, file=oup)
oup.write(line)
if "orange" in line:
number =1
print(number, file=oup)