【问题标题】:How to save the contents of text files as a list in json format sequentially (not concatenation)如何将文本文件的内容顺序保存为json格式的列表(不是串联)
【发布时间】:2017-11-08 17:59:54
【问题描述】:

我在一个目录中有数千个文本文件,并且希望将每个文件的内容保存在一个列表(一个大文件列表)中,同时保持文件在目录中的顺序。文本不得串联。请参阅我想要的输出示例。

Example=['textual content of file one', 'textual content of file two', 'textual content of file three'.....textual content of file n]

我的尝试:

filelist=[file-1,file-2,...file-n]
destinationfile="C:\\XXXXX\\dump_large_json.txt"
with open(destinationfile, 'w',encoding='utf-8') as f:
    for file in filelist:
        with open(file, 'r') as f2:
            h=json.dump(f2,f)

输出:

TypeError: 'TextIOWrapper' 类型的对象不是 JSON 可序列化的

任何关于如何以 json 格式串行转储文本文件的想法将不胜感激。

【问题讨论】:

  • 按照概述的类似程序,您需要阅读f
  • 这不是一个重复的问题,文本不要像你们指出的解决方案那样连接。
  • @cᴏʟᴅsᴘᴇᴇᴅ,这不是一个重复的问题,您指出我的解决方案涉及将文件上下文连接到一个大文件中,这不是我想要的。输出文件应该是一个包含每个文件的文本内容的列表。

标签: python json serialization text-files


【解决方案1】:

您需要将每个文件的文本内容附加到list,然后将生成的对象转储到json文件中:

filelist = [file-1, file-2, ... file-n]
destinationfile = "C:\\XXXXX\\dump_large_json.txt"

contents = []
for file in filelist:
    with open(file, 'r') as f:
        contents.append(f.read())

with open(destinationfile, 'w', encoding='utf-8') as f:
    json.dump(contents, f)

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2015-06-24
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 2022-11-10
    相关资源
    最近更新 更多