我正在寫一個小腳本,它將一個目錄中的大量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