Explanation about def rewind(f): f.seek(0)

Amirreza Yegane picture Amirreza Yegane · Oct 25, 2017 · Viewed 11.4k times · Source

i was reading a book and there was a code which had a this line in it

def rewind(f):
    f.seek(0)

and this is a line that i can't understand can you please explain me what is going on ?

 from sys import argv

script, input_file = argv

def print_all(f):
    print f.read()

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print line_count, f.readline()

current_file = open(input_file)

print " first lets print the whole file:\n"

print_all(current_file)

print "now lets rewind, kind of like a tape."

rewind(current_file)

print "lets print three lines:"

current_line = 1
print_a_line(current_l, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

-im using python 2.7

thanks for your time

Answer

Joe Iddon picture Joe Iddon · Oct 25, 2017

I would try reading this post on tutorials point.

The top of the article should help you out:

fileObject.seek(offset[, whence])

The method seek() sets the file's current position at offset. The whence argument is optional and defaults to 0, which means absolute file positioning; other values are: 1, which means seek relative to the current position, and 2, which means seek relative to the file's end.

So in your code this is called inside the function rewind(), which is called on this line:

rewind(current_file)

in which:

f.seek(0)

is called.

So what it does here in your code is move the current position in the file to the start (index 0). The use of this in the code is that on the previous lines, the entire file was just read, so the position is at the very end of the file. This means that for future things (such as calling f.readline()), you will be in the wrong place, whereas you want to be at the beginning - hence the .seek(0).