您好,谢谢您的时间。 我最近一直试图通过学习Python 2.7 Zed A. Shaw“学习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 it kind off like a tape."
rewind(current_file)
print "let's print three lines."
current_line = 1
print_a_line(current_line, current_file)
current_line += 1
print_a_line(current_file, current_file)
current_line += 1
print_a_line(current_line, current_file)
结果是:
First let's print the whole file:
To all the people out there.
I say I don't like my hair.
I need to shave it off.
Now let's rewind it kind off like a tape.
let's print three lines.
1 To all the people out there.
<open file 'test.txt', mode 'r' at 0x01D16230> I say I don't like my hair.
3 I need to shave it off.
除了<open file 'test.txt', mode 'r' at 0x01D16230>
之外,一切都工作得很好,这对我的单纯思维似乎是随机的。
为什么会出现这种情况?
注意:我在Windows 8.1上使用notepad ++
答案 0 :(得分:1)
print_a_line(current_file, current_file)
这应该是
print_a_line(current_line, current_file)
你看到的输出是因为
print line_count
其中line_count实际上是指之前为阅读而打开的文件流。