首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IO.UnsupportedOperation:不可写

IO.UnsupportedOperation:不可写
EN

Stack Overflow用户
提问于 2016-01-17 22:45:55
回答 3查看 22.5K关注 0票数 4

我制作了一个程序,它在.txt文件中存储一个带有名称的分数。然而,我想然后打印字母顺序的名称附加到分数。但是,当我运行这个程序时,它会产生错误io.UnsupportedOperation: not writable,这里是我的代码:

代码语言:javascript
复制
            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()
EN

回答 3

Stack Overflow用户

发布于 2016-01-18 09:54:56

您已打开文件只读,然后尝试写入它。当文件未打开时,您将尝试从其中读取,即使处于追加模式,文件指针也将位于文件的末尾。试一试:

代码语言:javascript
复制
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()
票数 5
EN

Stack Overflow用户

发布于 2016-01-17 22:55:54

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

代码语言:javascript
复制
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()); 
票数 1
EN

Stack Overflow用户

发布于 2016-01-18 09:33:12

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34844688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档