我制作了一个程序,它在.txt文件中存储一个带有名称的分数。然而,我想然后打印字母顺序的名称附加到分数。但是,当我运行这个程序时,它会产生错误io.UnsupportedOperation: not writable,这里是我的代码:
file = open(class_name , 'r') #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
lineList = file.readlines()
for line in sorted(lineList):
print(line.rstrip());
file.close()发布于 2016-01-18 09:54:56
您已打开文件只读,然后尝试写入它。当文件未打开时,您将尝试从其中读取,即使处于追加模式,文件指针也将位于文件的末尾。试一试:
class_name = "class.txt"
name = "joe"
score = 1.5
file = open(class_name , 'a') #opens the file in 'append' mode so you don't delete all the information
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
file.close()
file = open(class_name , 'r')
lineList = file.readlines()
for line in sorted(lineList):
print(line.rstrip());
file.close()发布于 2016-01-17 22:55:54
您正在尝试多次关闭该文件。试试这个:
with open(class_name , 'w+') as file:
name = (name)
file.write(str(name + " : " )) #writes the information to the file
file.write(str(score))
file.write('\n')
for line in sorted(lineList):
print(line.rstrip()); 发布于 2016-01-18 09:33:12
您正在以读模式r打开文件,这只允许读取文件,r+允许读取和写入文件。您可以参考python文档
https://stackoverflow.com/questions/34844688
复制相似问题