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
爲什麼會發生這種情況?
你能告訴我們該文件的內容。 –
無法用包含這三行的示例文件重現。也許你的輸入文件有文本編輯器無法識別的換行符?嘗試'print(repr(file.read()))' – poke
這是行1 這是行2 這是行3 –