66650

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 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?

Answer1:

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()

Answer2:

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

Answer3:

readlines() returns a list of <strong>all</strong> 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

Answer4:

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' 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.

Recommend

  • Most efficient way to convert a ISO Date into Unix timestamp?
  • How to get localized Windows Administrators group name in Inno Setup?
  • Strange file-permissions if apps run as administrator
  • RVM, Ruby 1.9.2, Rails 3, Passenger 3.0.2 (Bundler::GemNotFound)
  • Serial communication over USB converter in Python - how to aproach this?
  • file read() const correctness
  • Why won't EF4 generate a method to support my Function Import?
  • What is the official release update URL for Aptana Studio 3.0?
  • What does certain JVM do after loading ByteCode into memory?
  • Converter from SAT to 3-SAT
  • How can i dump blob fields from mysql tables
  • CERN ROOT exporting data to plain text
  • Calling Worksheet functions from vba in foreign language versions of Excel
  • Excel's Macro-Recorder usage
  • Marklogic : Query response time is very high
  • Mysterious problem with floating point in LISP - time axis generation
  • How to know when stdin is empty if it contains EOF?
  • Can I check if a recipient has an automatic reply before I send an email?
  • Regex thinks I'm nesting, but I'm not
  • C# - Is there a limit to the size of an httpWebRequest stream?
  • Optimizing database types to compact database (SQLite)
  • Finding past revisions of files in StarTeam w/ .NET SDK / C#
  • TFS: Get latest causes slow project reloading
  • Java applet as stand-alone Windows application?
  • Fill an image in a square container while keeping aspect ratio
  • Running a C# exe file
  • How to handle AllServersUnavailable Exception
  • VBA Convert delimiter text file to Excel
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Jquery - Jquery Wysiwyg return html as a string
  • Rearranging Cells in UITableView Bug & Saving Changes
  • align graphs with different xlab
  • Return words with double consecutive letters
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • SQL merge duplicate rows and join values that are different
  • Binding checkboxes to object values in AngularJs
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize
  • How to load view controller without button in storyboard?