未知错误消息

2024-05-13 22:56:21 发布

您现在位置:Python中文网/ 问答频道 /正文

尝试输出到文本文件时出现以下错误:

 io.UnsupportedOperation: not writable.

我的代码:

    def PostCodeStore(self):
       #Opens the Postcode file in append mode
       file = open("PostCode_File.txt", "r")

       PostCodeValue= PostCodeVar.get()

       #Writes the Postcode value to the file and adds a new line
       file.write(PostCodeValue + "\n")

       #Closes the file so it saves the value
       file.close()

Tags: the代码ioselfvaluedef错误not
2条回答

原因是无法写入用'r'打开的文件。必须用'a'打开。根据文件:

The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending; any data written to the file is automatically added to the end. 'r+' opens the file for both reading and writing. The mode argument is optional; 'r' will be assumed if it’s omitted.

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

这是一个常见的问题,而且(如文档中所示),在编写交叉兼容程序时可能会导致一些问题,因为Windows对二进制文件有不同的权限集。您可能不会使用二进制文件(可能是zipfiles),所以我不会太担心这个问题。记住:

'w'  # Writing
'r'  # Reading (default)
'a'  # Appending
'r+' # Read/Write

我相信我正确理解你的问题。也就是说,你的程序想要写很多行,一次一行(append)。如果您不想这样做,只想在文件中有一个带有换行符的条目,那么您将需要使用'w'。你知道吗

另外(顺便说一句),Python类名通常以大写字母开头。这就是PostCodeValue以不同格式显示的原因。按照惯例,这样的变量应该用小写字母和下划线命名,比如post_code_value。你知道吗

你错了

   file = open("PostCode_File.txt", "r")#Opens the Postcode file in append mode

r模式下,以只读方式打开文件,而不是附加。那就是a。你知道吗

相关问题 更多 >