IO.UnsupportedOperation:不可写

时间:2016-01-17 22:45:55

标签: python file

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

3 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

您正尝试多次关闭该文件。试试这个:

with open(class_name , 'r') 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()); 

答案 2 :(得分:1)

您正在以读取模式r打开文件,该模式仅允许读取文件r+允许读取和写入文件。您可以参考python documentation