IO.UnsupportedOperation:不可写

新手上路,请多包涵

我制作了一个程序,它在 .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()

原文由 Nasrullah Khan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 777
1 个回答

您以只读方式打开文件,然后尝试写入。在文件保持打开状态的情况下,您然后尝试从中读取,即使它处于追加模式,文件指针也会位于文件末尾。试试这个:

 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()

原文由 Rolf of Saxony 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题