python怎样将数据写入文件_python - 如何将JSON数据写入文件?

python - 如何将JSON数据写入文件?

我将JSON数据存储在变量TypeError: must be string or buffer, not dict中。

我想将其写入文本文件进行测试,因此我不必每次都从服务器中获取数据。

目前,我正在尝试这个:

obj = open('data.txt', 'wb')

obj.write(data)

obj.close

我收到错误:

TypeError: must be string or buffer, not dict

如何解决这个问题?

user1530318 asked 2018-12-24T19:26:58Z

12个解决方案

1464 votes

你忘了实际的JSON部分 - data是一个字典,还没有JSON编码。 写这样:

import json

with open('data.json', 'w') as outfile:

json.dump(data, outfile)

注意:适用于3.x和2.x.

phihag answered 2018-12-24T19:27:08Z

221 votes

要获得utf8编码的文件,而不是在Python 2的接受答案中使用ascii编码,请使用:

import io, json

with io.open('data.txt', 'w', encoding='utf-8') as f:

f.write(json.dumps(data, ensure_ascii=False))

Python 3中的代码更简单:

import json

with open('data.txt', 'w') as f:

json.dump(data, f, ensure_ascii=False)

在Windows上,dump的indent=4, sort_keys=True参数仍然是必需的。

为避免在内存中存储数据的编码副本(结果为indent=4, sort_keys=True)并在Python 2和3中输出utf8编码的字节串,请使用:

import json, codecs

with open('data.txt', 'wb') as f:

json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

indent=4, sort_keys=True调用在Python 3中是多余的,但Python 2需要

可读性和大小:

使用indent=4, sort_keys=True可提供更好的可读性和更小的尺寸:

>>> json.dumps({'price': '€10'})

'{"price": "\\u20ac10"}'

>>> json.dumps({'price': '€10'}, ensure_ascii=False)

'{"price": "€10"}'

>>> len(json.dumps({'абвгд': 1}))

37

>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))

17

通过将标志indent=4, sort_keys=True(由dinos66建议)添加到dump或dumps的参数来进一步提高可读性。这样,您将在json文件中获得一个很好的缩进排序结构,但代价是稍大的文件大小。

Antony Hatchkins answered 2018-12-24T19:27:59Z

140 votes

我会用前面提到的答案稍作修改来回答,那就是编写一个美化的JSON文件,人眼可以更好地阅读。 为此,通过sort_keys作为True和indent与4个空格字符,你很高兴去。 还要注意确保不会在您的JSON文件中写入ascii代码:

with open('data.txt', 'w') as outfile:

json.dump(jsonData, outfile, sort_keys = True, indent = 4,

ensure_ascii = False)

ambodi answered 2018-12-24T19:28:20Z

90 votes

使用Python 2 + 3读写JSON文件; 适用于unicode

# -*- coding: utf-8 -*-

import json

# Make it work for Python 2+3 and with Unicode

import io

try:

to_unicode = unicode

except NameError:

to_unicode = str

# Define data

data = {'a list': [1, 42, 3.141, 1337, 'help', u'€'],

'a string': 'bla',

'another dict': {'foo': 'bar',

'key': 'value',

'the answer': 42}}

# Write JSON file

with io.open('data.json', 'w', encoding='utf8') as outfile:

str_ = json.dumps(data,

indent=4, sort_keys=True,

separators=(',', ': '), ensure_ascii=False)

outfile.write(to_unicode(str_))

# Read JSON file

with open('data.json') as data_file:

data_loaded = json.load(data_file)

print(data == data_loaded)

.json的参数说明:

.json:使用4个空格缩进每个条目,例如 当一个新的dict启动时(否则所有都将在一行),

.json:对字典的键进行排序。 如果要将json文件与diff工具进行比较/将它们置于版本控制之下,这非常有用。

.json:防止Python添加尾随空格

随着包

看看我的实用程序包.json,它是一个超级简单易记的实用程序:

import mpu.io

data = mpu.io.read('example.json')

mpu.io.write('example.json', data)

创建了JSON文件

{

"a list":[

1,

42,

3.141,

1337,

"help",

"€"

],

"a string":"bla",

"another dict":{

"foo":"bar",

"key":"value",

"the answer":42

}

}

常见文件结尾

.json

备择方案

CSV:超简单格式(读取和写入)

JSON:很适合编写人类可读的数据; 非常常用(读和写)

YAML:YAML是JSON的超集,但更容易阅读(读取和写入,JSON和YAML的比较)

pickle:Python序列化格式(读取和写入)

MessagePack(Python包):更紧凑的表示(读和写)

HDF5(Python包):很适合矩阵(读和写)

XML:存在*叹气*(读和写)

对于您的应用程序,以下可能很重要:

其他编程语言的支持

读/写性能

紧凑性(文件大小)

另请参见:数据序列化格式的比较

如果您正在寻找一种制作配置文件的方法,您可能希望阅读我的简短文章Python中的配置文件

Martin Thoma answered 2018-12-24T19:30:21Z

19 votes

对于那些试图抛弃希腊语或其他“异国情调”语言的人,例如我,但也有问题(unicode错误)与奇怪的字符,如和平符号(\ u262E)或其他通常包含在json格式数据中 比如Twitter,解决方案可能如下(sort_keys显然是可选的):

import codecs, json

with codecs.open('data.json', 'w', 'utf8') as f:

f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))

dinos66 answered 2018-12-24T19:30:42Z

10 votes

我没有足够的声誉来添加评论,所以我只是在这里写下我讨厌的TypeError的一些发现:

基本上,我认为它只是Python 2中的TypeError: must be unicode, not str函数中的一个错误 - 它无法转储包含非ASCII字符的Python(字典/列表)数据,即使您使用data参数打开该文件也是如此。 (即无论你做什么)。 但是,json.dumps()适用于Python 2和3。

为了说明这一点,请跟进phihag的答案:如果data包含非ASCII字符,则他的答案中的代码会在Python 2中出现,例外情况为TypeError: must be unicode, not str。 (Python 2.7.6,Debian):

import json

data = {u'\u0430\u0431\u0432\u0433\u0434': 1} #{u'абвгд': 1}

with open('data.txt', 'w') as outfile:

json.dump(data, outfile)

然而,它在Python 3中运行良好。

ibic answered 2018-12-24T19:31:16Z

7 votes

使用JSON使用json.dump()或json.dumps()在文件中写入数据。这样写就是将数据存储在文件中。

import json

data = [1,2,3,4,5]

with open('no.txt', 'w') as txtfile:

json.dump(data, txtfile)

列表中的此示例存储到文件中。

Vishal Gediya answered 2018-12-24T19:31:40Z

4 votes

json.dump(data, open('data.txt', 'wb'))

Alexander answered 2018-12-24T19:31:55Z

2 votes

如果您尝试使用json格式将pandas数据帧写入文件,我建议这样做

destination='filepath'

saveFile = open(destination, 'w')

saveFile.write(df.to_json())

saveFile.close()

Franco Miguel Contreras answered 2018-12-24T19:32:15Z

0 votes

以前的所有答案都是正确的,这是一个非常简单的例子

#! /usr/bin/env python

import json

def write_json():

# create a dictionary

student_data = {"students":[]}

#create a list

data_holder = student_data["students"]

# just a counter

counter = 0

#loop through if you have multiple items..

while counter < 3:

data_holder.append({'id':counter})

data_holder.append({'room':counter})

counter += 1

#write the file

file_path='/tmp/student_data.json'

with open(file_path, 'w') as outfile:

print("writing file to: ",file_path)

# HERE IS WHERE THE MAGIC HAPPENS

json.dump(student_data, outfile)

outfile.close()

print("done")

write_json()

1CNhG.png

nanoseconds answered 2018-12-24T19:32:35Z

0 votes

接受的答案很好。 但是,我使用它遇到了“不是json serializable”错误。

这是我修复它的方法使用open(“file-name.json”,“w”)作为输出:

output.write(STR(响应))

虽然它不是一个好的修复,因为它创建的json文件不会有双引号,但是如果你正在寻找快速和脏的话,这是很好的。

Akshat Bajaj answered 2018-12-24T19:33:09Z

0 votes

可以按如下方式将JSON数据写入文件

hist1 = [{'val_loss': [0.5139984398465246],

'val_acc': [0.8002029867684085],

'loss': [0.593220705309384],

'acc': [0.7687131817929321]},

{'val_loss': [0.46456472964199463],

'val_acc': [0.8173602046780344],

'loss': [0.4932038113037539],

'acc': [0.8063946213802453]}]

写入文件:

with open('text1.json', 'w') as f:

json.dump(hist1, f)

Ashok Kumar Jayaraman answered 2018-12-24T19:33:34Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值