简体   繁体   中英

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. I am using 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() ,

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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