Python open和with open的区别

1,583 阅读1分钟

读写文件是一个IO操作,open打开一个文件对象,使用python内置的open函数

f = open('text.txt', 'r')

若文件不存在,open()会抛出IOError的错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'

若文件打开成功,可用read()方法可以一次读取文件的全部内容,Python把内容读到内存,用一个str表示。 最后一步是调用close()方法关闭文件。文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源,并且操作系统同一时间打开的文件数量也是有限的,因此了有了如下的写法

try:
    f = open('text.txt', 'r')
    print(f.read())
finally: // finally内的代码无论有无异常发生,都会执行
    if f:
       f.close()    

同时有了简化的写法

with open('text.txt', 'r') as f:
    print(f.read())

开发中推荐使用with open