看python源码定义:
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
mode参数:
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
常用模式:
1、想要写数据到文件,用w或a
#清空原有内容写入
with open(file,mode='w') as f:
f.write()
#在原有文件后追加写入
with open(file,mode='a') as f:
f.write()
写入文件不会直接写入磁盘,需要关闭文件后,再写入,所以用with open() as f这种更加合理,防止忘记关闭文件
2、想要读取文件内容,用r模式
根据读的文件大小,选择合适的读方法
1 #文件较小:一次读文件全部 f.read()
with open(file,mode='r') as f:
f.read()
2 #文件较大:可以选择一行一行的读或者指定字节大小的读
with open(file,mode='r') as f:
f.read(1024) # 1024单位为字节
#readlines需要配合循环使用
with open('../datas/pointCounts.yml','r',encoding="utf-8") as f;
for lines in f.readlines():
print(lines.strip())
3、想要操作视频、二进制文件,用b
常用于读取读取一个二进制文件后,在写入另一个文件,类似复制粘贴
with open('../datas/testbinary.yml', 'wb') as f:
f.write(fileobj)