我正在读一本书,里面有一段代码,里面有一行
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)使用Python2.7的-im
耽误您时间,实在对不起
发布于 2017-10-25 20:04:14
我会尝试在tutorials point上阅读this post。
这篇文章的顶部应该会对你有所帮助:
fileObject.seek(offset[, whence])
seek()方法在offset处设置文件的当前位置。whence参数是可选的,默认为0,表示绝对文件定位;其他值有: 1,表示相对于当前位置的查找;2,表示相对于文件末尾的查找。
因此,在您的代码中,这是在函数rewind()中调用的,该函数在下面的代码行中调用:
rewind(current_file)其中:
f.seek(0)是调用的。
因此,它在您的代码中所做的就是将文件中的当前位置移动到开头(索引0)。它在代码中的用途是,在前面的行中,整个文件刚刚被读取,因此该位置位于文件的最末尾。这意味着对于将来的事情(例如调用f.readline()),您将处于错误的位置,而您希望处于开始位置-因此使用.seek(0)。
发布于 2018-05-23 09:29:01
如果您更改为def rewind(F),您的文件中有一些更改: f.seek(2)您无法看到input_file..in终端的前两个字母,而不是在原始文件中
https://stackoverflow.com/questions/46931833
复制相似问题