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 line) by each of them. This is the code:
filename = 'text_file_example.txt' myfile = open(filename,'r') myfile.readlines(5) print(myfile.readlines(5)) myfile.close()
Would it be better to read one line in a for(range 5) loop?
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()
according to documentation:
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
so your best option is to use a for loop:
for line in myfile.readlines()[:5]: print line
readlines() returns a list of <strong>all</strong> lines,so you should probably do:
But as it loads all lines it is not memory efficient.
So, a better solution here will be to use
list(islice(myfile,5)) # it'll return a list of first five lines, # no need of reading all lines
If you want to limit the number of lines read, use the file object as an iterable, then slice the lines using
import itertools filename = 'text_file_example.txt' with open(filename,'r') as myfile: # skip five list(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.