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)
我有这段代码,这行得通,但我不明白的是,当我将打印行函数中的打印语句重写为 print(file.readline(line)) 时,我得到了一个意外的输出。我正在使用 python 3.6
正确的输出
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
为什么会这样?
这是因为 的函数定义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.
因此,当您将行号作为参数传递时,您实际上是在告诉每个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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句