gpt4 book ai didi

python json转储可写性 "not write able"

转载 作者:行者123 更新时间:2023-11-30 21:49:53 27 4
gpt4 key购买 nike

所以这是我的程序的第二个问题,但是是一个完全不同的问题,感谢那位乐于助人的人建议 JSON 作为一种更好的方法来完成我想要的事情......

无论如何...

JSON 取得了一些成功。该程序也改变了主题,我绝对不想制作游戏,只是获得灵感以了解更多有关 python 中“保存”概念的信息..所以这是我到目前为止的代码,有一个有效的 JSON 编码文件可供读取..但我遇到了另一个障碍,当我尝试使用 JSON 的 .dump 方法时,它报告此错误

错误:

Traceback (most recent call last):
File "<string>", line 1, in <module>
File "<string>", line 32, in <module>
File "/data/data/com.hipipal.qpy3/files/lib/python3.2/python32.zip/json/__init__.py", line 177, in dump
io.UnsupportedOperation: not writable

代码:

import os
import random
import json
with open("/storage/emulated/0/com.hipipal.qpyplus/scripts3/newgame2.txt") as data_file:
data = json.load(data_file)
save=data
print(save)
hero=dict(save)
print(hero)
level=int(0)
job=str("none")
experience=int(0)
strength=int(0)
intelligence=int(0)
dexterity= int(0)
health= int(0)
magic= int(0)
luck= int(0)
if hero["level"]==0:
level=int(0)
job=str("none")
experience=int(0)
strength=int(0)
intelligence=int(0)
dexterity= int(0)
health= int(0)
magic= int(0)
luck= int(0)
hero=[("level",level), ("job",job), ("experience",experience), ("strength",strength), ("intelligence",intelligence), ("dexterity",dexterity), ("health",health), ("magic",magic), ("luck",luck)]
hero=dict(hero)
with open("/storage/emulated/0/com.hipipal.qpyplus/scripts3/newgame2.txt") as data_file:
json.dump(hero, data_file)

最佳答案

您没有在“写入模式”下打开文件。

尝试将您的 open() 行更改为:

with open("/storage/emulated/0/com.hipipal.qpyplus/scripts3/newgame2.txt", "w") as data_file:
json.dump(hero, data_file)

默认情况下Python的内置open()以“读取”模式打开文件。

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.

关于python json转储可写性 "not write able",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30158322/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com