2015-05-11 5 views
1

Итак, это вторая часть проблемы с моей программой, но совершенно другая проблема, благодаря полезному человеку, который предложил JSON как лучший способ делать то, что я хотел. ..python json dump writeability «not write able»

Во всяком случае ...

некоторый успех с JSON. Программа также изменила тему, я определенно не привязываюсь к игре, просто получаю вдохновение, чтобы узнать больше о концепции «сохранения» в python .. так вот мой код до сих пор, с действительным кодированным файлом JSON для чтения из .. но я побежал в другую корягу, он сообщает эту ошибку, когда я пытаюсь использовать метод .dump JSON «s

Ошибка:

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) 
+1

Ваш код является абсолютным беспорядком, вы должны отформатировать его должным образом. – Raniz

ответ

1

Вы не открывать файл в режиме "записи".

Попробуйте изменить 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.

+0

Спасибо Джеймс .. мой сотовый телефон действительно засасывает при правильном форматировании, и я здесь новый ... Мне жаль, что все это заняло, но спасибо, что сообщение прошло. –

+0

@ RyanHarger you 're welcome :) –

+1

Замечательно видеть ответ, который действительно приносит сюда полезную информацию из ссылки и делает ее автономной. – Santiago

1

Изменения открытого line, чтобы включить '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