with语句
with语句的作用
with语句可以自动调用关闭文件操作,即使出现异常也会自动调用。
普通文件操作
f = open('test.txt', 'w')
f.write('hello world')
f.close()
with文件操作
with open('test.txt', 'w') as f:
f.write('hello world')
with语句可以自动调用关闭文件操作,即使出现异常也会自动调用。
f = open('test.txt', 'w')
f.write('hello world')
f.close()
with open('test.txt', 'w') as f:
f.write('hello world')