f=open('/Users/michael/notfound.txt', 'r')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/Users/michael/notfound.txt'
为了弥补异常,我们一般用try finally来处理未知的异常
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
所以文件操作一般就是定义一个变量 给变量指向引用对象,open(file_name),然后调用各种操作read文件内容给字符串或者列表对象,最后使用完了记得关闭close()文件鉴于以上复杂的流程,一部到位的好东西with open as file比较好
语法
:with open() as file:
file.read()
好搓就是不用自己try finally ,然后系统自己判断异常,
with open('digui.py',mode='r+',encoding='utf-8') as myfile:
print(myfile.read())
IBM比较牛的解释
使用 with 语句操作文件对象
with open(r'somefileName') as somefile:
for line in somefile:
print line
这里使用了 with 语句,不管在处理文件过程中是否发生异常,都能保证 with 语句执行完毕后已经关闭了打开的文件句柄。如果使用传统的 try/finally 范式,则要使用类似如下代码:
清单 3. try/finally 方式操作文件对象
somefile = open(r'somefileName')
try:
for line in somefile:
print line
finally:
somefile.close()
比较起来,使用 with 语句可以减少编码量。已经加入对上下文管理协议支持的还有模块 threading、decimal 等。