====================1
class Test:
def __enter__(self):
print "\n-----in __enter__---self-----", self
return self
def __exit__(self, type, value, traceback):
print "\n-------in __exit__----self, type, value, traceback-----",
self, type, value, traceback
with Test() as thing:
print "\n-----in with------", thing
OUTPUT
======
-----in __enter__---self----- <__main__.Test instance at 0x7f98f1ebfe60>
-----in with------ <__main__.Test instance at 0x7f98f1ebfe60>
-------in __exit__----self, type, value, traceback----- <
__main__.Test instance at 0x7f98f1ebfe60> None None None
====================2
fp = open("my_file", "r")
print "\n------fp--------", fp
fp.__enter__()
print "\n------fp--------", fp
data = fp.readline()
print "\n------data--------", data
fp.__exit__()
print "\n------fp--------", fp
data = fp.readline()
OUTPUT
======
------fp--------
------fp--------
------data-------- hello #data red from file
------fp--------
Traceback (most recent call last):
File "py_with.py", line 23, in
data = fp.readline()
ValueError: I/O operation on closed file
====================3
so to open a file, process its contents, and make sure to close it, you can simply do:
with open("my_file") as fp:
data = fp.read()
do something with data
====================
More
No comments:
Post a Comment