在确定性上积累,在不确定性上低成本试错!|

FreeCheng

园龄:3年9个月粉丝:0关注:1

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

 

本文作者:FreeCheng

本文链接:https://www.cnblogs.com/freecheng/p/17456223.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   FreeCheng  阅读(66)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起