Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to go the start of file in python?

Tags:

python

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.

like image 606
Suraj Nagabhushana Ponnaganti Avatar asked Oct 12 '16 17:10

Suraj Nagabhushana Ponnaganti


1 Answers

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.

like image 187
MooingRawr Avatar answered Sep 20 '22 13:09

MooingRawr