尝试输出到文本文件时出现以下错误:
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()
原因是无法写入用
'r'
打开的文件。必须用'a'
打开。根据文件:这是一个常见的问题,而且(如文档中所示),在编写交叉兼容程序时可能会导致一些问题,因为Windows对二进制文件有不同的权限集。您可能不会使用二进制文件(可能是zipfiles),所以我不会太担心这个问题。记住:
我相信我正确理解你的问题。也就是说,你的程序想要写很多行,一次一行(append)。如果您不想这样做,只想在文件中有一个带有换行符的条目,那么您将需要使用
'w'
。你知道吗另外(顺便说一句),Python类名通常以大写字母开头。这就是
PostCodeValue
以不同格式显示的原因。按照惯例,这样的变量应该用小写字母和下划线命名,比如post_code_value
。你知道吗你错了
在
r
模式下,以只读方式打开文件,而不是附加。那就是a
。你知道吗相关问题 更多 >
编程相关推荐