【问题标题】:Python I/O: Mixing The DatatypesPython I/O:混合数据类型
【发布时间】: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')。
  • 谢谢 :) 很高兴在这里获得您的专业知识

标签: python json file-io types


【解决方案1】:

如果这是 Python 3,删除 b(二进制模式)以在 文本模式 中打开文件应该可以正常工作。您可能想明确指定编码:

with open("test.json", "w", encoding='utf8') as outfile:
    json.dump(data, outfile, sort_keys = True, indent = 2, ensure_ascii = False)

而不是依赖默认值。

你真的不应该使用codecs.getreader()。标准的open() 函数可以很好地处理UTF-8 文件;只需以文本模式打开文件并再次指定编码:

import glob
import json

for file in glob.glob("/Users/me/Scripts/BagOfJson/*.json"):
    with open(file, "r", encoding='utf8') as infile:
        data = json.load(infile)
        with open("test.json", "w", encoding='utf8') as outfile:
            json.dump(data, outfile, sort_keys = True, indent = 2, ensure_ascii = False)

上面仍然会为*.json glob 中的每个文件重新创建test.json;无论如何,您都不能真正将多个 JSON 文档放在同一个文件中(除非您专门创建 JSONLines files,因为您使用的是 indent,所以您没有在这里创建)。

如果您想重新格式化 glob 中的所有 JSON 文件,则需要写入新文件名并将新文件名移回 file 文件名。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多