I am new to python and I am learning some basic file reading stuff. I am trying to read a file and count the number of new lines and also print lines that start with 'From: ' .
This is the code I have for that:
fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count + 1
print count
for line in fhand:
if line.startswith('From: '):
print line
I know that I can do this in one loop but I am trying to learn something here. As soon as the first loop is executed, 'line' is at the end of the file. So when it runs the second loop, it does not print anything. I tried putting in line = 0, it doesnt work. How to I got back to start of file?
Thank you for your help.
file.seek(0)
seek() takes an argument that goes back to that "byte" so 0 byte will go back to the start of the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With