Reading the Contents of a File

To read the content of a file we must first open the file in read mode.


The file handle is given to f. We can perform actions on the file using the handle f. ‘r’ specifies that the file is opened in read mode. That filed is optional. If not given, the interpreter assumes the file to be opened in read mode. ‘w’ opens the file in write mode, ‘r+’ in read and write mode, ‘a’ in append mode.

  • : returns the entire file as a string.
  • f.readline() : returns line by line as a string.
  • f.readlines() : returns a list of strings.

Another way to read a file line by line is:

>>> for line in f:

…        print line

  • : goto the 6th byte of the file.
  •,2) : goto the 3rd byte from the last.
  •,1) : go forward by 2 byte from the current position.
  • f.close() : To close the file and the resources allocated for file operation will be freed up.

Another way of reading is by using with :

>>> with open(‘location’,’mode’) as f:

…     data=read()

>>> f.closed



About Odol Shinu

I've completed my B Tech in Information Technology in 2010 from Government Engineering College Sreekrishnapuram Palakkad under Calicut University.

Posted on August 29, 2010, in Python. Bookmark the permalink. 1 Comment.

  1. thanx man!! was lookin for the same!!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: