【问题标题】:Explanation about def rewind(f): f.seek(0)关于 def rewind(f) 的解释:f.seek(0)
【发布时间】:2017-10-25 11:57:45
【问题描述】:

我在看一本书,里面有一段代码

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)

-我使用 python 2.7

感谢您的宝贵时间

【问题讨论】:

  • rewind(current_file): 使用了你的倒带功能。删除它会使您的代码无法正常工作。
  • 您查找过seek 的文档吗?这应该告诉你你需要知道的一切。
  • 没有rewind(),你得到了什么输出。你期待什么?它绝对不会做任何事情......另外请发布您运行的实际代码。您发布的代码包含拼写错误。
  • rewind(f) kind of 模拟做同样事情的 C 函数。如果你问我不是很有用,因为f.seek(0) 足够清楚

标签: python function seek rewind


【解决方案1】:

我会尝试在tutorials point 上阅读this post

文章的顶部应该可以帮助你:

fileObject.seek(offset[, whence])

seek() 方法将文件的当前位置设置为offsetwhence 参数是可选的,默认为0,表示绝对文件定位;其他值是:1,表示相对于当前位置进行搜索,以及 2,表示相对于文件末尾进行搜索

所以在您的代码中,这在函数rewind() 中被调用,该函数在这一行被调用:

rewind(current_file)

其中:

f.seek(0)

被调用。

所以它在您的代码中所做的是将文件中的当前位置移动到 startindex 0)。在代码中使用 this 是在前几行中,整个文件只是被读取,所以位置在文件的最后。这意味着对于未来的事情(例如调用f.readline()),您将处于错误的位置,而您希望在开始 - 因此.seek(0)

【讨论】:

    【解决方案2】:

    如果您更改为 def 倒带(f): f.seek(2) 你看不到你的 input_file..in TERMINAL 的前两个字母 不在原始文件中

    【讨论】:

    • 请提供您打算更改的代码并清楚说明,谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    • 2010-10-06
    • 2015-04-29
    • 2013-04-28
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多