python打开文件时的mode选择

发布时间 2023-06-04 20:16:57作者: FreeCheng

常用:

追加:a

覆盖:w

Mode Description Example
r Read mode. Opens the file for reading (default mode). If the file doesn’t exist, an error will be raised. file = open('example.txt', 'r')
w Write mode. Opens the file for writing. If the file exists, it will be truncated. If the file doesn’t exist, it will be created. file = open('example.txt', 'w')
a Append mode. Opens the file for writing, but appends new data to the end of the file instead of overwriting existing data. If the file doesn’t exist, it will be created. file = open('example.txt', 'a')
x Exclusive creation mode. Opens the file for writing, but only if it doesn’t already exist. If the file exists, an error will be raised. file = open('example.txt', 'x')
b Binary mode. Opens the file in binary mode instead of text mode. file = open('example.txt', 'rb')
t Text mode (default). Opens the file in text mode instead of binary mode. file = open('example.txt', 'rt')
+ Update mode. Opens the file for both reading and writing. file = open('example.txt', 'r+')