2017-06-07 11 views
1

私はからPythonを学んでいます。Python The Hard Wayを学んでください。これは与えられた演習の1つですが、私の出力はの内容と一致しません。セクションを参照してください。ここで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()'がその値を取得する前に出力していると思います。 print文の前に余分な行を追加してみてください。 'myLine = f.readline()'、 'print line_count、myLine'です。 – 16num

+2

print_allの出力から、 "this is line1"と "this is nice line2"の間に空白行があることがわかります。これはprint_a_lineへの2度目の呼び出しで印刷しています。おそらく、いくつかの改行の変換が間違っているか、またはコピーの貼り付けエラーですか? –

答えて

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 

(空行で)、あなたは、単に(グローバル変数CURRENT_LINEが効果的に増加されることを意味します)、「2」で始まる空行を印刷:

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

@バルドック:完了。 –

+0

ありがとうございました!私はこの間違いをするのはとても馬鹿だ!私は空白行も数えていることを完全に忘れました。たくさんありがとう! @ lecaruyer –

関連する問題