How to read a text file line by line

Reading one line at a time.


print "\nReading one line at a time."
text_file = open("read_it.txt", "r")
print text_file.readline()
print text_file.readline()
print text_file.readline()
text_file.close()# ww w. j  a va  2  s .c om


f = open(r'c:\text\somefile.txt') 
for i in range(3): 
   print str(i) + ': ' + f.readline(), 
f.close() 

import pprint 
pprint.pprint(open(r'c:\text\somefile.txt').readlines()) 

Read lines into a list


filePath = "input.txt"
# from  w w  w . j a  va 2  s .c  o  m
buffer = "Readline buffer:\n"
inList = open(filePath, 'rU').readlines()
print inList
for line in inList:
    buffer += line
print buffer

Looping through the file, line by line.


print "\nLooping through the file, line by line."
text_file = open("read_it.txt", "r")
for line in text_file:
    print line# from w  w  w  .  j  ava  2s .c  om
text_file.close()

Determining the Number of Lines in a File


filePath = "input.txt"

lineCount = len(open(filePath, 'rU').readlines())
print "File %s has %d lines." % (filePath,lineCount)

Read a file line by line and check line separator


import sys#   ww w .  j av  a 2 s  .co  m
try:
       f = open(sys.argv[1], "rb")
except:
       print "No file named %s exists!" % (sys.argv[1],)
while 1:
       t = f.readline()
       if t == '':
           break
       if '\n' in t:
           t = t[:-1]
       if '\r' in t:
           t = t[:-1]
       sys.stdout.write(t + '\n')
f.close()

Handle File reading Exception


import sys#   ww w  . ja  v  a 2  s.co  m

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module