我正在写一个小脚本,它将一个目录中的大量JSON文件合并到一个文件中。麻烦的是,我不完全确定我的数据处于何种状态。类型错误比比皆是。这是脚本;Python I/O:混合数据类型
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 – Typhon