python基础--with-as

来源:互联网 发布:mui.picker.min.js 编辑:程序博客网 时间:2024/05/29 04:03

python中的IO操作,内置读写文件函数,用法兼容了C。

python 读写操作

读文件

>>>f=open('/local/hello.txt','r')#不存在抛出IOError>>>f.read()#存在读出所有内容>>>f.read(size)#读取size大小,避免过大>>>f.readline()#读取单行内容>>>f.close()

为了获取到Exception内容,一般用try—catch结构,并且保证能最终关闭文件finally

try:    f=open('/local/hello.txt','r')    print(f.read())Exception e:    print efinally:    if f:        f.close()

每次这样写太繁琐,python引入了with语句自动调用close()方法。

with open('/local/hello.txt'.'r') as f:    print(f.read())#多个文件可以写成with open() as if:    with open as if:        ...        ...        ...#或with open() as f:    ...with open() as f:    ...
原创粉丝点击