我正在读一本书,里面有一行代码
def rewind(f):
f.seek(0)
这是一条我无法理解的路线你能解释一下发生了什么吗?
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使用python 2.7
谢谢你的时间
tutorials point
.文章的顶部应该帮助你:
fileObjecy.seek(offset[, whence])
方法
seek()
将文件的当前位置设置为偏移量。 whence参数是可选的,默认为0,表示绝对文件定位,其他值为1表示相对于当前位置的搜索,2表示相对于文件结束的搜索。
所以在你的code
中,它被称为rewind
函数,在这个line
上调用:
rewind(current_file)
其中:
f.seek(0)
叫做。
所以它在你的代码中所做的就是将position
中的当前file
移动到开头(index
0
)。在代码中使用这个是在以前的lines
,整个file
只是read
,所以position
是在file
的最后。这意味着对于未来的事情(例如调用f.readline()
),你将在错误的地方。虽然你想成为开始 - 因此.seek(0)
。
如果你更改为def rewind(f),你的文件会有变化:f.seek(2)你看不到input_file的前两个字母..在TERMINAL NOT in ORILEINAL FILE