IO.UnsupportedOperation:不可写

Nas*_*han 3 python file

我制作了一个程序,它在一个.txt文件中存储一个附有名称的分数。但是,我想然后打印附加到乐谱的名称的字母顺序。但是当我运行程序时,它出现了错误io.UnsupportedOperation: not writable Here my code:

            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()
Run Code Online (Sandbox Code Playgroud)

Rol*_*ony 5

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

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()
Run Code Online (Sandbox Code Playgroud)