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

python json dump writability "not write able"

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

总之...

JSON 取得了一些成功。该程序也改变了主题,我绝对不是为了制作游戏,只是获得灵感来了解更多关于 python 中 "saving" 的概念。所以这是我到目前为止的代码,具有有效的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)

将打开的行更改为包含 'w',它告诉 Python 以写入模式打开文件

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

https://docs.python.org/3.4/library/functions.html#open

您没有在 "write mode" 中打开文件。

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

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

默认情况下 Python 的内置 open() 以 "read" 模式打开文件。

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.