7/9 The 'with' and 'as' Keywords


So, not exactly having issues with my coding, but a general questions for any of experienced Python gurus out there!
I guess there are 2 ways for writing/reading file. One method is opening a file, writing data and closing it. The other “with” “as” method opens and closes automatically…So the question is…

Why would anyone use ( 3 lines of code!!)
write_file = open(“text.txt”, “w”)
write_file.write(“Not closing files is VERY BAD.”)

OVER (2 lines of code that a ALSO closes automagically)
with open(“text.txt”, “w”) as textfile:

Can anyone explain why we shouldn’t just use the second method all the time? Why does the first method even exist in the first place…?



The with and as keywords do provide a convenience, but they are also limiting in some regards. Note that this line serves as a block header …

with open("text.txt", "w") as textfile:

Everything within the block needs to be indented. Once the block ends, the file closes. However, you may not always want a file to close automatically. In some complex programs that contain conditional blocks, you may wish to keep a file open until some condition occurs, and then close the file at that time. In such situations, it might be best to close the file explicitly at a point that is determined at run time, rather than relying on the with and as keywords to do it automatically.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.