2017-04-16 52 views
0
from sys import argv 

script,inputfile=argv 

def print_all(file): 
    print(file.read()) 

def rewind(file): 
    file.seek(0) 

def print_line(line,file): 
    print(line,file.readline()) 

currentFile=open(inputfile) 

print("Let's print the first line: \n") 

print_all(currentFile) 

print("Rewind") 
rewind(currentFile) 

currentLine=1 

print_line(currentLine,currentFile) 

currentLine+=1 

print_line(currentLine,currentFile) 


currentLine+=1 


print_line(currentLine,currentFile) 

我有這段代碼,這個工程,但我不明白的是,當我重寫打印語句在打印行函數打印(file.readline(line))我得到意想不到的輸出。我使用Python 3.6python readline沒有給出預期的輸出

正確的輸出

This is line 1 
This is line 2 
This is line 3 
Rewind 
This is line 1 

This is line 2 

This is line 3 

不正確的輸出

This is line 1 
This is line 2 
This is line 3 
Rewind 
T 
hi 
s i 

爲什麼會發生這種情況?

+1

你能告訴我們該文件的內容。 –

+0

無法用包含這三行的示例文件重現。也許你的輸入文件有文本編輯器無法識別的換行符?嘗試'print(repr(file.read()))' – poke

+0

這是行1 這是行2 這是行3 –

回答

1

這是因爲file.readline()函數定義的,

readline(...) 
    readline([size]) -> next line from the file, as a string. 

    Retain newline. A non-negative size argument limits the maximum 
    number of bytes to return (an incomplete line may be returned then). 
    Return an empty string at EOF. 

因此,當傳遞線數作爲參數,你是actullay告訴它獲取與每個currentLine+=1遞增字節數。

如果你只是打算打印由線內容行,你可以參考這個,

def print_file_line_by_line(currentFile): 
    for line in currentFile: 
     print line.strip('\n') 

或者這也適用

def print_file_line(currentLine, currentFile): 
    try: 
     print currentFile.read().split('\n')[currentLine-1] 
    except IndexError as e: 
     print str(currentLine)+' is greater than number of lines in file' 
     print ''+str(e) 
+0

但OP永遠不會傳遞行號。 OP只統計他們打印的行號*與文件中的下一行一起。 'currentLine'永遠不用於與文件進行交互。 – poke

+0

@poke:我認爲OP在說謊他們的代碼。這是他們得到的輸出的唯一明智的解釋,所以得到感謝我的upvote – Eric

+0

@Eric正如我在對問題的評論中解釋的那樣,輸入文件可能具有OP的文本編輯器不可見的字符這算作換行符到'readline'。即使OP在說謊他們的代碼,他們在問題中顯示的代碼是*非常好*並且完全按預期工作,所以這個答案沒有幫助。 – poke