1. 对文件读写
import codecs
fout = codecs.open('test.html', 'w', encoding='UTF-8')
fout.write('<html>')
fout.write('</html>'
fout.close()
很自然地可将其改造为 with 结构,with 结构会自动执行 fout 的 close() 方法(查阅 codecs 的源码发现,codecs.open 方法返回的 StreamReaderWriter 对象内部实现了 __enter__和__exit__方法):
with codecs.open(filename, 'w', encoding='utf-8') as fout:
fout.write(...)
本文介绍了如何利用Python中的with结构来优化文件读写操作,这种方法可以确保文件被正确关闭,即使在文件操作过程中发生异常也能自动调用close()方法。通过示例展示了将传统文件打开方式改进为更简洁且安全的with语句形式。

被折叠的 条评论
为什么被折叠?



