Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过ex20艰难地学习Python,这个函数是如何工作的?_Python - Fatal编程技术网

通过ex20艰难地学习Python,这个函数是如何工作的?

通过ex20艰难地学习Python,这个函数是如何工作的?,python,Python,我学习python之前没有任何编码经验,这是我现在不理解的 以下是全部代码: 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

我学习python之前没有任何编码经验,这是我现在不理解的

以下是全部代码:

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 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)
最后一部分应按如下方式打印:

Now let's rewind, kind of like a tape.
Let's print three lines:
1 This is line 1
2 This is line 2
3 This is line 3

我不明白的是最后几行。“当前文件”块如何理解它必须首先只打印一行,其次它如何知道它应该与“当前文件”所需的行相同?

每次调用
.readline()
,文件对象都会前进;
current\u line
变量仅用于提供行号。这两者并没有真正的联系

尝试删除
current\u line=current\u line+1
行,它将打印:

Now let's rewind, kind of like a tape.
Let's print three lines:
1 This is line 1
1 This is line 2
1 This is line 3
你可以想象,
current\u line
是你自己的记事本,记下一个数字,只是为了验证行确实在前进。如果你忘了记下下下一个数字,文件就不管了,不管怎样都会继续

文件很像磁带;每次读取时,读写“头”沿着“磁带”前进,以便下一次读取或写入操作在该新位置发生

“head”只是一个数字,文件中的位置,由操作系统管理。您始终可以向文件询问当前位置。如果在
print\u a\u line()
函数中添加
print f.tell()
行,它将打印此时头部的位置

最后但并非最不重要的一点是,正如
rewind()
函数已经显示的那样,允许您将“头部”重新定位到新位置
f.seek(0)
将其放回起始位置