Python open()、with open()
open()
- 打开文件
f = open('/Users/michael/test.txt', mode='r')
- mode的各种模式
模式
|
可做操作
|
若文件不存在
|
是否覆盖
|
r
|
只读
|
error
|
-
|
r+
|
读写
|
error
|
T
|
w
|
只写
|
create
|
T
|
w+
|
读写
|
create
|
T
|
a
|
只写
|
create
|
F,尾部追加写
|
a+
|
读写
|
create
|
F,尾部追加写
|
wb
|
只写二进制字符串,写入bytes
|
create
|
T
|
rb
|
只读二进制字符串,返回bytes
|
error
|
-
|
- 关闭文件
1 try: 2 f = open('/path/to/file', 'r') 3 print(f.read()) 4 finally: 5 if f: 6 f.close()
with open()
- 操作单个文件
1 with open("test/test.py", "a+") as f: 2 f.write("test")
- 用with同时操作多个文件
1 with open("test/test.py", 'r') as f1, open("test/test2.py", 'r') as f2: 2 print(f1.read()) 3 print(f2.read())
open() 与 with open() 区别
- open需要主动调用close(),with不需要
- open读取文件时发生异常,没有任何处理,with有很好的处理上下文产生的异常