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

Question:

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

Asked By: Amirreza Yegane

||

Answers:

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).

Answered By: Joe Iddon

there is something change in your file if you change to
def rewind(f):
f.seek(2)
you cannot see first two letter of your input_file..in TERMINAL
NOT IN ORIGINAL FILE

Answered By: Niranjan
from sys import argv

script, input_file = argv
def print_all (f):
    print(f.read())

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

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

current_file = open(input_file)

print("First let's print the whole file:n")
print_all(current_file)
print("Now let's rewind, kind of like a tape.")

rewind(current_file)
print("Let's print three lines:")

current_line = 1
print_a_line(current_line, 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)#Pay attention to how we pass in the current line number each time we run print_a_line.
Answered By: Sangram Bahadur
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.