我犯的错误是什么?

时间:2017-06-07 12:01:53

标签: python

我从学习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()有问题吗?这不是第一次发生这种情况。

1 个答案:

答案 0 :(得分:1)

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

没有空行:

2

在你的情况下(空行),你只需打印以“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 this is line2. This must be printed!!

3 this is line3.This is cool!Print please