Explaining Python’s ‘__enter__’ and ‘__exit__’

Using these magic methods (__enter__, __exit__) allows you to implement objects which can be used easily with the with statement. The idea is that it makes it easy to build code which needs some ‘cleandown’ code executed (think of it as a try-finally block). Some more explanation here. A useful example could be a database connection object (which then automagically closes … Read more

File open and close in python

The mile-high overview is this: When you leave the nested block, Python automatically calls f.close() for you. It doesn’t matter whether you leave by just falling off the bottom, or calling break/continue/return to jump out of it, or raise an exception; no matter how you leave that block. It always knows you’re leaving, so it … Read more

Using “with open() as file” method, how to write more than once? [duplicate]

The w flag means “open for writing and truncate the file”; you’d probably want to open the file with the a flag which means “open the file for appending”. Also, it seems that you’re using Python 2. You shouldn’t be using the b flag, except in case when you’re writing binary as opposed to plain text content. In Python 3 your … Read more