python打开文件时的mode选择

追加:a

覆盖:w

读取:r

“+”存在的意义:

r+:可读可写,若文件不存在,报错;

  • 以读写方式打开文件。
  • 文件指针位于文件的开头。
  • 可以进行读取和写入操作,但写入操作会从文件当前位置开始覆盖原有内容。
  • 如果文件不存在,则会抛出 FileNotFoundError 异常

w+: 可读可写,若文件不存在,创建;

  • 以读写方式打开文件,如果文件不存在则创建文件。
  • 如果文件存在,则会清空文件内容,将文件指针置于文件开头。
  • 可以进行读取和写入操作,写入操作会覆盖原有内容。
  • 如果文件不存在,则会创建新文件。

参考:python文件打开方式详解——a、a+、r+、w+区别-腾讯云开发者社区-腾讯云 (tencent.com)

使用f.seek(0)可以将指针移到开头,避免追加写入a+模式下(写入后指针位于文件最末尾)时使用f.read()内容为空的问题。

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+')

 

posted @ 2023-06-04 20:14  FreeCheng  阅读(104)  评论(0)    收藏  举报