Leandra
Leandra

Reputation: 1

Back to the top of file?

I have a program where I'm reading numbers from a file and adding those numbers to different lists in my program. Now, I need to jump back to the top of the file and read from the top again. Does anyone know if there is a command that does that or if its even possible?

Upvotes: 0

Views: 549

Answers (2)

Afiz
Afiz

Reputation: 503

There are couple of ways to achieve this. Simplest one is using seek(0). 0 represents start of the file.

You can even use tell() to store any position of the file and reuse it:

with open('file.txt', 'r') as f:
    first_position = f.tell()
    f.read() # your read 
    f.seek(first_position)  # it will take you to the previous position you marked. 

Upvotes: 0

Ahasanul Haque
Ahasanul Haque

Reputation: 11144

You can use seek(0) to start from the beginning all over again.

Actually, when you read from a file, it continuously updates the offset to the current bytes. seek() provides you with the ability to set the offset at any position.

At the beginning, offset is located at 0. So, f.seek(0) will set the offset at the beginning of the file.

with open('filename','r') as f:
    f.read(100) # Read first 100 byte     
    f.seek(0) # set the offset at the beginning
    f.read(50) # Read first 50 byte again.

Upvotes: 1

Related Questions