How do i go back to the top of a text file in 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.

asked Oct 12, 2016 at 17:21

How do i go back to the top of a text file in python?

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.

How do i go back to the top of a text file in python?

answered Oct 12, 2016 at 17:23

1

Try this out :

with open('mbox.txt') as f:
    count = 0
    for l in f.readlines():
        count += 1
        if l.startswith('From: '):
            print l

To get back to start of file use seek(0)

answered Oct 12, 2016 at 17:23

How do i go back to the top of a text file in python?

MMFMMF

5,5423 gold badges15 silver badges19 bronze badges

1 minute read

This is something I used to stumble on a lot in the early days of my Python coding adventure so I thought to write a quick article about it.

Python Open file

Opening a file for read or write in Python can be achieved with the following code:

# Open file
file = open("/Python/Files/MyFile.txt")

Python Read file

To read content of the file we simply use the read() method

# Read file to the end of file
file.read()

'This is the first line\nAnd a second\nAnd even a third\nShall we put a fourth?\nWhy not a fifth\nOr a sixt\n'

Note that Python will print the newline character and will not split lines for you (but that’s material for another day/post)

Where is my text?

Say you want to print again file content issue the same command again will leave you with something like this

# Read file again
file.read()
''

Not a lot to see on screen, so where did our file’s content go?

Python seek()

When python reads a file’s content it will move file current position to the end of the file so trying to re-read it again will yield the above result. Nothing as there is nothing else to read.

You can easily go back to the beginning of the file with the seek() method which is used like this:

# Go back to position 0
# Or beginning of file
file.seek(0, 0)

  • Syntax of seek() method fileObject.seek(offset[, whence])

  • offset is the position of the read/write pointer within the file.

  • whence is optional and defaults to 0 which means absolute file positioning, other possible values are 1 which means seek relative to the current position and 2 which means seek relative to the file’s end

Now if you try to read the file again all content will be correctly displayed

file.read()

'This is the first line\nAnd a second\nAnd even a third\nShall we put a fourth?\nWhy not a fifth\nOr a sixt\n'

How do I go back to the top of a file in Python?

We can move the file pointer to the beginning of the file using the seek() method by passing the setting whence to 0. The 0 indicates the first byte, which is the beginning of the file.

How do you get to the beginning of a text file in Python?

seek() takes an argument that goes back to that "byte" so 0 byte will go back to the start of the file. of note... If your are both reading and writing (mode r+ ), an easy way to go back to the end of the file (presumably to append to it) is to call seek(-1) .

How do I go back to a step in Python?

Your "go back a step" operation is what's commonly referred to as a GoTo, probably the most hated operation in any programming language. It is not supported in Python, you must use other methods like loops. You go back by using loops, like those while loops you have.

How do you write to top of file in Python?

To prepend content to a file in Python, open the file in read+write mode, seek to the start of the file, then write the newline plus the original file content.