如何在json文件中写入数据?

2024-05-23 19:18:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在json文件中写入数据?这是我的尝试:

from django.test import TestCase
from django_dynamic_fixture import G
import content.factories
from django.core import serializers
from content.models import UserProfile, Delivery
from django.contrib.auth.models import User

class DeliveryTest(TestCase):
    def test_sample_data(self):
        for i in range(0,10):
            user = content.factories.UserFactory.create()
            print user
            for j in range(0, 50):
                delivery = content.factories.DeliveryFactory.create(user=user)
                print delivery

                with open("file.json", "w") as out:
                    data = serializers.serialize("json", User.objects.all() ) 

                with open("file.json", "w") as out:
                    data2 = serializers.serialize("json", Delivery.objects.all() )

输出(打印):http://dpaste.com/hold/923339/


Tags: djangofromtestimportjsonfordatamodels
1条回答
网友
1楼 · 发布于 2024-05-23 19:18:18

实际上,您并不是在编写数据,而是转换为JSON。对打开的文件调用.write()

with open("file.json", "w") as out:
    data = serializers.serialize("json", User.objects.all())
    out.write(data)
    data2 = serializers.serialize("json", Delivery.objects.all() )
    out.write(data)

只打开file.json一次;每次用'w'模式打开它进行写入时,它都会首先被擦除。在

或者,get a reference to the serializer并告诉它直接写入打开的文件:

^{pr2}$

哪个更有效。在

相关问题 更多 >