Skip to content

With

Writing to a file

stream = open('output.txt', 'wt')
stream.write('Lorem ipsum dolar')
stream.close()

重构上面的代码

try:
    stream = open('output.txt', 'wt')
    stream.write('Lorem ipsum dolar')
finally:
    stream.close()

Simplifying with with

with open('output.txt', 'wt') as stream:
    stream.write('Lorem ipsum dolar')