首页 > 解决方案 > 文件中带有“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

解决方案


推荐阅读