Ami*_*ane -1 python function seek rewind
我正在读一本书,有一个代码,里面有一行
def rewind(f):
f.seek(0)
Run Code Online (Sandbox Code Playgroud)
这是我无法理解的一行,你能解释一下发生了什么吗?
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)
Run Code Online (Sandbox Code Playgroud)
-im 使用 python 2.7
谢谢你的时间
tutorials point。The top of the article should help you out:
fileObject.seek(offset[, whence])The method
seek()sets the file's current position atoffset. Thewhenceargument 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)
Run Code Online (Sandbox Code Playgroud)
in which:
f.seek(0)
Run Code Online (Sandbox Code Playgroud)
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).