Sunday, February 2, 2014

When do we use Python's "with as"?

Generally, we use the below Python code with three lines to write data into a file.

f = open ("Test.txt", "w")
f.writelines (Lines)
f.close ()

Sometimes, we are lazy to use one line to do the same thing.

open ("Test.txt", "w").writelines (Lines)

That is OKAY. Data will be automatically written into the file because f.close() is automatically called when the Python program exits.

But there is a problem. The below second line cannot read any new data from the file because new data has not been written by the first line.

open ("Test.txt", "w").writelines (Lines)
Lines = open ("Test.txt").readlines ()

We found that Lines are empty because the file "Test.txt" is not closed.

We can use "with as" supported by Python 2.6 to solve the problem.

with open ("Test.txt", "w") as f:
    f.writelines (Lines)
Lines = open ("Test.txt").readlines ()

When the block of "with as" finishes, f.close() is automatically called. Therefore the third line can read data from the file into Lines.

We can refer the below page for more detail of "with as".
http://openhome.cc/Gossip/Python/WithAs.html

-Count

No comments:

Post a Comment