所以,我正在尝试在python 3.6中编写一个小程序来合并多个JSON文件(17k),我收到了上述错误。 我通过阅读其他SO Q& As来整理剧本。我玩了一下,得到了各种各样的错误,然而,我无法让它发挥作用。这是我的代码:
# -*- coding: utf-8 -*-
import glob
import json
import os
import sys
def merge_json(source, target):
os.chdir(source)
read_files = glob.glob("*.json")
result = []
i = 0
for f in glob.glob("*.json"):
print("Files merged so far:" + str(i))
with open(f, "rb") as infile:
print("Appending file:" + f)
result.append(json.load(infile))
i = i + 1
output_folder = os.path.join(target, "mergedJSON")
output_folder = os.path.join(output_folder)
if not os.path.exists(output_folder):
os.makedirs(output_folder)
os.chdir(output_folder)
with open("documents.json", "wb") as outfile:
json.dump(result, outfile)
try:
sys.argv[1], sys.argv[2]
except:
sys.exit("\n\n Error: Missing arguments!\n See usage example:\n\n python merge_json.py {JSON source directory} {output directory} \n\n")
merge_json(sys.argv[1], sys.argv[2])
答案 0 :(得分:0)
在您的情况下,您打开的文件是' wb'模式,这意味着它只适用于类字节对象。但是json.dump
正试图给它写一个字符串。您只需更改“wb'”中的打开模式即可。到了' w' (文字模式)它会起作用。