2017-06-07 51 views
1

我正在学Python从了解Python的艰难之路。这是给出的练习之一,但是我的输出结果与应该看到的内容部分不符。 Here is the output snap. The 2nd line is printed in number 3 and the 3rd line isn't printed at all.我在犯什么错误?

这里是我的代码:

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 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_line, current_file) 

current_line += 1 
print_a_line(current_line, current_file) 

是有一些问题,在我的系统readline()?这不是第一次发生这种情况。

+0

我跑你的代码似乎工作正常,如果我正确理解你。我运行python 2.7.12,OS Xubuntu 16.04。 – Nurjan

+0

我认为'print_a_line()'函数在f.readline()检索它的值之前打印它的输出。尝试在打印语句之前添加一行。 'myLine = f.readline()'然后'print line_count,myLine'。 – 16num

+2

从print_all输出中,您可以看到“this is line1”和“this is the nice line2”之间有一条空行,在第二次调用print_a_line时将打印此行。也许一些新行转换在某个时候出错了,或者复制了粘贴错误? –

回答

1

您的test.txt文件包含多个空白行。你必须删除它们,特别是在line1和line2之间。它会解决你的问题。

不空行:

First let's print the whole file: 

this is line1.Say hello. 
this is line2. This must be printed!! 
this is line3.This is cool!Print please 

now let's rewind, kind of like tape. 
Let's print three lines: 
1 this is line1.Say hello. 

2 this is line2. This must be printed!! 

3 this is line3.This is cool!Print please 

在你的情况(空行),您只需打印的空行开始与“2”(这意味着全局变量current_line有效增加):

First let's print the whole file: 

this is line1.Say hello. 

this is line2. This must be printed!! 

this is line3.This is cool!Print please 

now let's rewind, kind of like tape. 
Let's print three lines: 
1 this is line1.Say hello. 

2 

3 this is line2. This must be printed!! 
+0

注意到输入文件有空行的道具。 OP没有提供它,但当然提供了输出文件的输出的屏幕截图。 – Baldrickk

+0

@Baldrickk:完成。 –

+0

非常感谢!我犯这个错误真是太傻了!我完全忘了空白的行数太多..感谢很多! @lecaruyer –

相关问题