Python 如何在json文件中保存更改

Python 如何在json文件中保存更改,python,json,io,Python,Json,Io,我对实现删除方法有问题。Delete*方法应删除所有注释。示例:Note.objects.filter(board='in progress').delete()-应删除所有带有board“in progress”的便笺。对我来说,最大的问题是在json文件中保存更改问题是:当我用delete方法删除注释时,如何在json文件中保留更改? def delete(self): all_notes = [note for note in Note.objects.all()] # try

我对实现删除方法有问题。Delete*方法应删除所有注释。示例:Note.objects.filter(board='in progress').delete()-应删除所有带有board“in progress”的便笺。对我来说,最大的问题是在json文件中保存更改问题是:当我用delete方法删除注释时,如何在json文件中保留更改?

   def delete(self):
   all_notes = [note for note in Note.objects.all()] # try to delete note with index 1
   for note in all_notes:
        if note.id == 1:
           all_notes.pop(0)
   for note in all_notes:
       print note
       note.save()
以下是代码:

# coding: utf-8
from __future__ import unicode_literals
from shutil import copyfile
import json
import os

DATABASE = 'notes_data/notes.json'
BOARDS = ['to do', 'in progress', 'done']


class NotesManagerMixin(object):

    def count(self):
        return len(self.notes)

    def filter(self, *args, **kwargs):
        result = self.notes
        for key, value in kwargs.iteritems():
            result = [
                note for note in result
                if getattr(note, key, None) == value or 
                note.message.startswith(value) or 
                note.message.endswith(value)
            ]
        return NotesQueryset(result)

    def get(self, *args, **kwargs):
        notes = self.filter(**kwargs)
        if notes.count() == 0:
            raise IndexError('Note doesn\'t exist')
        elif notes.count() == 1:
            return notes[0]
        else:
            raise IndexError('Returned more then one entry')

    def first(self):
        return self.notes[0]

    def last(self):
        return self.notes[-1]


class NotesQueryset(NotesManagerMixin):

    def __init__(self, notes):
        self.notes = [note for note in notes]

    def update(self, *args, **kwargs):
        notes = self.notes
        for note in notes:
            if 'board' in kwargs:
                note.board = kwargs['board']
                note.save()
            if 'message' in kwargs:
                note.message == kwargs['message']
                note.save()



    def delete(self):
        all_notes = [note for note in Note.objects.all()] # try to delete note with index 1
        for note in all_notes:
            if note.id == 1:
                all_notes.pop(0)
        for note in all_notes:
            print note
            note.save()



    def __getitem__(self, idx):
        return self.notes[idx]

    def __str__(self):
        return str(self.notes)

    def __repr__(self):
        return self.__str__()


class NotesManager(NotesManagerMixin):

    def __init__(self):
        self.notes = []

    def __iter__(self):
        return self.next()

    def __generate_id(self):
        """
            Funkcja pomocnicza do pobrania pewnej wolnej wartości indexu.
        """
        try:
            return max(note.id for note in self.notes) + 1
        except ValueError:
            return 1

    def all(self):
        return NotesQueryset(self.notes)

    def add(self, idx, board, message):
        self.notes.append(Note(idx=idx, board=board, message=message))

    def create(self, board, message):
        note = Note(
            idx=self.__generate_id(),
            board=board,
            message=message
        )
        note.clean()

        self.notes.append(note)
        note.save()

        return note

    def next(self):
        for note in self.notes:
            yield note

    def to_dict(self):
        return [note.to_dict() for note in self.notes]


class Note(object):
    objects = NotesManager()

    def __init__(self, idx, board, message):
        self.id = idx
        self.board = board
        self.message = message

    def __str__(self):
        return 'ID: {}, Board: {}, Message: {}'.format(
            self.id,
            self.board,
            self.message
        )

    def __repr__(self):
        return self.__str__()

    def clean(self):
        if not self.message:
            raise ValueError('Message is required')

        if self.board not in BOARDS:
            raise ValueError('Board "{}" doesn\'t exists'.format(self.board))

        if type(self.id) != int:
            raise ValueError('Note id "{}" is invalid'.format(self.id))

    def save(self):
        for key, note in enumerate(self.objects):
            if note.id == self.id:
                self.objects.notes[key] = self
                break

        with open(DATABASE, 'w') as database_file:
            json.dump(self.objects.to_dict(), database_file, indent=4)

        return True

    def delete(self):
        # delete just one note
        pass

    def to_dict(self):
        return {
            'id': self.id,
            'message': self.message,
            'board': self.board
        }


def load_initial_data():

    with open(DATABASE, 'r') as database_file:
        json_data = json.load(database_file, encoding='utf-8')

    for item in json_data:
        Note.objects.add(
            idx=item['id'],
            board=item['board'],
            message=item['message'],
        )


load_initial_data()

通常,修改文件的方法是用修改过的数据覆盖整个文件。因此,一旦您修改了内存中的数据,您的
save
方法应该已经完成了您想要的操作


这里的问题是,
delete
不是修改要保存的
Note.objects
数据,而是修改由列表创建的临时数组
[Note.objects.all()中的Note for Note]。因此,当您调用
save
时,您将再次保存原始数据。

save方法可以很好地工作,但不能使用此方法,而且我不知道循环应该从何处开始:note in note.objects.all():您忘了问问题!对不起,现在好些吗?