Writing to a file

eryksun () eryksun at gmail.com
Fri Mar 25 22:28:35 EDT 2011


On Friday, March 25, 2011 9:39:11 PM UTC-4, Littlefield, Tyler wrote:
> >    with open(test_absname, 'w') as test:
> what's the difference in that and test = ...? I can see why you 
> mentioned the os.path for cross-platform, but I don't understand why 
> someone would use with over =.

It avoids having to write a try...finally block to close the file automatically and immediately in case of an error. Also, you can easily chain additional context managers into this syntax, such as for redirecting standard input/output to the file. More info here:

http://diveintopython3.org/files.html



More information about the Python-list mailing list