2020年8月13日 / 23次阅读 / Last Modified 2020年8月13日
有两种使用with语句操作文件的方式,使用with语句的目的是不用自己写close。
>>> with open('tw.txt', 'w') as f:
... f.write('hahaha...')
...
9
>>> f.tell()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
在with语句中以w的方式打开一个file,离开with语句时,自动执行了f.close()。
with语句还可以直接接一个已经打开的文件:
>>> f = open('tw.txt')
>>> with f: # or with f as g:
... f.read()
...
'hahaha...'
>>> f.tell()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: I/O operation on closed file.
同样,在离开with语句的时候,自动执行了f.close()。
继续学习:with mutex的用法
with后面还可以接多个对象,用法如下:
>>> with open('tw.txt') as f, open('bb','w') as g:
... g.write(f.read())
...
9
>>> with open('bb') as f:
... print(f.read())
...
hahaha...
-- EOF --
本文链接:https://www.pynote.net/archives/2350
Ctrl+D 收藏本页
©Copyright 麦新杰 Since 2019 Python笔记