简体   繁体   English

Python readline没有给出预期的输出

[英]Python readline not giving expected output

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)

I have this code, this works but what I don't understand is when I rewrite the print statement in the print line function to print(file.readline(line)) I get an unexpected output. 我有这段代码,可以正常工作,但是我不明白的是,当我将打印行函数中的打印语句重写为print(file.readline(line))时,得到了意外的输出。 I am using python 3.6 我正在使用python 3.6

correct output 正确的输出

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

incorrect output 输出不正确

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

why does this happen? 为什么会这样?

This is because of the function definition of file.readline() , 这是因为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.

Hence, when you pass line number as an argument, you are actullay telling the number of bytes which gets incremented with each currentLine+=1 . 因此,当您将行号作为参数传递时,您会用算数法告知每个currentLine+=1递增的字节数。

If you just intend to print the contents line by line, you can refer this, 如果您只是打算逐行打印内容,可以参考此内容,

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

or this also works 或者这也有效

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM