python - 文件中带有“r+”参数的错误
问题描述
我在 r+ 参数方面遇到了一些问题,我不明白为什么在 python 版本 2 和 3 中都会发生这种情况。
使用“w”和“r”效果很好(注意:文件预先存在)
f = open("file.txt", "w")
f.write("Hello ladies\nand gentlemen.")
f.close()
f = open("file.txt", "r")
print(f.readlines())
f.close()
但是,使用带有“r+”参数的等效方法会返回错误(注意:文件预先存在)
f = open("file.txt", "r+")
f.write("Hello ladies\nand gentlemen")
print(f.readlines())
f.close()
Python 2 中的错误
Traceback (most recent call last):
File "C:/...", line 4, in <module>
print(f.readlines())
IOError: [Errno 0] Error
Python 3 中的错误*
Traceback (most recent call last)
File "C:...", line 4, in <module>
print(f.readlines())
File "C:...\AppData\Local\Programs\Python\Python39\lib\encodings\cp1252.py", line 26, in decode
return codecs.charmap_decode(input, self.errors, decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 2526: character maps to
<undefined>
为什么会出现这种情况?
解决方案
推荐阅读
- python - 从每组中找到最近三个数据点的斜率
- php - 我的 PHP 代码很慢,如何让它变快?
- azure - 在 DevOps 实施期间无法获取托管服务主体的访问令牌
- azure-devops-server-2019 - 计划在 azure devops 中的下一次清理作业期间永久删除
- javascript - 如何在 discord.js 中将 Connect perm 设置为默认值?
- struct - 了解 Python 的 struct pack/unpack 函数
- php - 从 MySQL 获取输入变量并将输出发送到 Arduino
- variables - 如何检测变量是否已在 Pascal 脚本中声明?
- azure - Azure 函数应用部署错误“在主机运行时遇到错误 (ServiceUnavailable)。(代码:400)”
- javascript - 在我的 Django 项目中,如何动态地将位于静态文件夹中的脚本附加到头部?