首页 > 解决方案 > 为什么显示 io.UnsupportedOperation: not writable

问题描述

导入pygame,随机

定义相当游戏():

readFile = open("BestScore.txt")
bestScoreFile = readFile.read()
readFile.close()
writeFile = open("BestScore.txt")
iScore = max(score,int(bestScoreFile))
print('Your Score is :', score)
print('Highest Score is :', iScore)
writeFile.write(str(iScore))
writeFile.close()
pygame.quit()

为什么那里显示消息“ writeFile.write(str(iScore)) io.UnsupportedOperation: not writable”。

标签: pythonfilewrite

解决方案


为了写入文件,您需要使用“可写”模式打开它。默认情况下,python.txt以“只读”模式打开任何文件

要以可写模式打开文件,请执行以下操作:

writeFile = open("BestScore.txt","w") #Opens BestScore.txt in writable mode
[...]#Other code

所以最终的代码应该是这样的:

import pygame, random

def quiteGame():

    readFile = open("BestScore.txt")
    bestScoreFile = readFile.read()
    readFile.close()
    writeFile = open("BestScore.txt","w")
    iScore = max(score,int(bestScoreFile))
    print('Your Score is :', score)
    print('Highest Score is :', iScore)
    writeFile.write(str(iScore))
    writeFile.close()
    pygame.quit()

推荐阅读