How do I read each line of a file and add if statements?
Question:
I’m pretty new to Python, but I’m trying to learn. One idea I had for a simple script was to have a script that reads and writes to a log file during execution. Then based on what’s in that log file, helps dictate what the script does the next time it’s ran.
Reading and writing to a file seems simple enough in Python,
f = open('textfile.txt', 'r+')
Reading and print out each line of a file seems simple too,
for line in f:
print line
line=f.next()
print line
But, how do I incorporate an IF statement when reading a file to do something based on what was read?
for line in f
if line == '1':
print "Works!"
else:
print line
line=f.next()
print line
f.close()
Output
1
2
3
4
5
Answers:
The problem is that line is equal to
'1n'
You first need to remove the newline character by doing first in your loop:
line = line.rstrip()
Another possibility could be, in this particular case in which you expect integers, to cast the line string into an integer, and then to compare to an integer:
line = int(line)
if line == 1:
# and so on
I’m pretty new to Python, but I’m trying to learn. One idea I had for a simple script was to have a script that reads and writes to a log file during execution. Then based on what’s in that log file, helps dictate what the script does the next time it’s ran.
Reading and writing to a file seems simple enough in Python,
f = open('textfile.txt', 'r+')
Reading and print out each line of a file seems simple too,
for line in f:
print line
line=f.next()
print line
But, how do I incorporate an IF statement when reading a file to do something based on what was read?
for line in f
if line == '1':
print "Works!"
else:
print line
line=f.next()
print line
f.close()
Output
1
2
3
4
5
The problem is that line is equal to
'1n'
You first need to remove the newline character by doing first in your loop:
line = line.rstrip()
Another possibility could be, in this particular case in which you expect integers, to cast the line string into an integer, and then to compare to an integer:
line = int(line)
if line == 1:
# and so on