Skip to content Skip to sidebar Skip to footer

Reading Document Lines To The User (python)

I'm trying to write a program to read 5 lines of a text document to the user, but I can't manage to get it to work. It currently prints line 4 and line 5 along with the '\n' (new l

Solution 1:

The builtin function you are using, readlines() does the following (from the official documentation):

f.readlines() returns a list containing all the lines of data in the file. If given an optional parameter sizehint, it reads that many bytes from the file and enough more to complete a line, and returns the lines from that.

Perhaps you might want to do that:

filename = 'text_file_example.txt'
myfile = open(filename,'r')
file_lines = myfile.readlines()
for line in file_lines[:5]: 
    print(line)
myfile.close()

Solution 2:

according to documentation:

If given an optional parameter sizehint, 
it reads that many bytes from the file and 
enough more to complete a line, andreturns the lines from that

so your best option is to use a for loop:

for line in myfile.readlines()[:5]:
    print line

Solution 3:

readlines() returns a list of all lines,so you should probably do:

lines=myfile.readlines()[:5]

But as it loads all lines it is not memory efficient.

So, a better solution here will be to use itertools.islice:

list(islice(myfile,5)) # it'll return a list of first five lines,# no need of reading all lines

Solution 4:

If you want to limit the number of lines read, use the file object as an iterable, then slice the lines using itertools.islice:

import itertools

filename = 'text_file_example.txt'withopen(filename,'r') as myfile:
    # skip fivelist(itertools.islice(myfile, 5))
    print(*itertools.islice(myfile, 5), sep='', end='')  # print 5, use newlines from file

Note that we pass the 5 read lines to the print() function as a series of arguments, not as one object, using the * syntax, then disable the automatic space and newline characters; the lines do not need to be separated by spaces and already include newlines.

The above code will only ever read 10 lines of your file, regardless of how large it is. Calling .readlines() will (try to) read the whole file into memory, regardless of size and available memory.

Post a Comment for "Reading Document Lines To The User (python)"