How to read text file

Reading the entire file at once


print "\nReading the entire file at once."
text_file = open("read_it.txt", "r")
whole_thing = text_file.read()# from  w w w .  j  av  a  2  s  . c o  m
print whole_thing
text_file.close()

Read characters

Tell the stream how many characters (bytes) you want to read.


f = open('somefile.txt', 'r') 
print f.read(4) 
print f.read() 
f.close() 

The code above generates the following result.





















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module