faqts : Computers : Programming : Languages : Python : Modules : file

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

22 of 24 people (92%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

How can I read all the lines from a file?
How can I detect end-of-file when reading it?

Mar 2nd, 2000 16:15
Nathan Wallace, Mike Fletcher, ze, Steve Holden


There are a number of ways to approach this problem.

First approach:

  file = open( filename )
  line = file.readline()
  while line:
        doprocessing( line )
        line = file.readline()

The first call to readline() which returns an empty string indicates
you have hit the end of the file.  Empty lines in the file are
returned as strings with the newline still in them.  Don't forget
that every line you actually read has the newline in it, too!

Second approach:

  import fileinput
  file = fileinput.FileInput( filename )
  for line in file:
        doprocessing(line)

This one is straight from the standard tutorial, Chapter 7. Say you want
to read from a file named "file.txt", and print each line. Just do:

  input=open('file.txt','r')     #open file.txt for reading
  while 1:
    newline = input.readline()   #read a line
    if newline == '': break   #is it empty? you've hit eof. stop reading
    print newline             #else, print the line

Unless the files are too large to consider this, the readlines() file
method is easier to use.