【发布时间】:2016-08-18 13:54:42
【问题描述】:
我正在编写一个小脚本,它将一个目录中的大量 JSON 文件合并到一个文件中。麻烦的是,我不完全确定我的数据何时处于哪种状态。类型错误比比皆是。这是脚本;
import glob
import json
import codecs
reader = codecs.getreader("utf-8")
for file in glob.glob("/Users/me/Scripts/BagOfJson/*.json"):
#Aha, as binary here
with open(file, "rb") as infile:
data = json.load(reader(infile))
#If I print(data) here, looks like good ol' JSON
with open("test.json", "wb") as outfile:
json.dump(data, outfile, sort_keys = True, indent = 2, ensure_ascii = False)
#Crash
此脚本导致以下错误;
TypeError: a bytes-like object is required, not 'str'
这是由 json.dump 行引起的。
天真我只是删除'wb'中的'b'以打开outfile。这样做是不行的。
也许这对我来说是一个教训,让我使用 shell 进行测试,并使用 type() python 函数。不过,如果有人能为我弄清楚这些数据交换背后的逻辑,我会很高兴。我希望它都可以是字符串...
【问题讨论】:
-
删除
'b'后发生了什么?您是否收到了不同的错误? -
另外,这是 Python 2 还是 Python 3?
-
@MartijnPieters 好吧,Martijn,我会告诉你当我删除“wb”中的“b”时会发生什么。有用。在我尝试的时候,我一定有另一个错误。谢谢你的明智问题!这是python 3
-
是的,在 Python 3 中,
json.dump()总是写入 Unicode 字符串,因此您希望将其写入文本文件(所以没有'b')。 -
谢谢 :) 很高兴在这里获得您的专业知识