Python readings – Compound – with and as

One of the compound statement in python is “with” and “as” combination. Here a context manager is used with respect to the with block to save and restore “global state, locking and unlocking resources, closing opened files, etc”.global state, locking and unlocking resources, closing opened files, etc.

The context manager has two methods entry and exit. Here when a file is opened in the entry, then the file will be closed automatically when it the block exits.

object.__enter__(self)

object.__exit__(self, exc_type, exc_value, traceback)

 

#!/usr/bin/python
import os

print "With - Compound statement"
fileName = os.getcwd()+"/"+__file__
print fileName

with open(fileName, "r") as f:
   print f.readlines()
   print "\n"
   f.seek(0)
   print "\n"
   print f.readlines()

Leave a Reply

Your email address will not be published. Required fields are marked *