So this is the second piece of a problem with my program, but a completely different issue, thanks to the helpful person who suggested JSON as a better method to do what I wanted....
Anyway...
some success with JSON. The program also changed theme, I definitely am not tying to make a game, just get the inspiration to learn more about the concept of "saving" in python.. so here's my code so far, with a valid JSON coded file to read from.. but I ran into another snag, it reports this error when I try to use the JSON 's .dump method
Error:
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
Code:
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)
You are not opening your file in "write mode".
Try to change your open()
line to this:
with open("/storage/emulated/0/com.hipipal.qpyplus/scripts3/newgame2.txt", "w") as data_file:
json.dump(hero, data_file)
By default Python's builtin open()
opens files in "read" mode.
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.
Change the open line to include 'w' which tells Python to open the file in write mode
with open("/storage/emulated/0/com.hipipal.qpyplus/scripts3/newgame2.txt", 'w') as data_file:
json.dump(hero, data_file)
来源:https://stackoverflow.com/questions/30158322/python-json-dump-writability-not-write-able