Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么显示io.UnsupportedOperation:不可写_Python_File_Write - Fatal编程技术网

Python 为什么显示io.UnsupportedOperation:不可写

Python 为什么显示io.UnsupportedOperation:不可写,python,file,write,Python,File,Write,导入pygame,随机 def quiteGame(): 为什么会有消息“writeFile.write(str(iScore)) io.UnsupportedOperation:not writable(不可写)显示在此处。要写入文件,您需要以“writable(可写)”模式打开它。默认情况下,python以“只读”模式打开任何.txt文件 要以可写模式打开文件,请执行以下操作: writeFile=open(“BestScore.txt”,“w”)#以可写模式打开BestScore.txt

导入pygame,随机

def quiteGame():

为什么会有消息“writeFile.write(str(iScore))
io.UnsupportedOperation:not writable(不可写)显示在此处。

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

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

writeFile=open(“BestScore.txt”,“w”)#以可写模式打开BestScore.txt
[…]#其他代码
因此,最终的代码应该如下所示:

导入pygame,随机
def quiteGame():
readFile=open(“BestScore.txt”)
bestScoreFile=readFile.read()
readFile.close()
writeFile=open(“BestScore.txt”、“w”)
iScore=max(分数,整数(最佳分数文件))
打印('您的分数为:',分数)
打印('最高分数为:',iCore)
writeFile.write(str(iScore))
writeFile.close()
pygame.quit()

非常感谢您。是的,我将成功解决此问题并修复错误。如果此答案对您有所帮助,则您必须单击勾选按钮接受答案
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()