如何将文本文件的内容按顺序保存为json格式的列表(不是串联)

2024-07-05 14:03:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我在一个目录中有数千个文本文件,我想在一个列表(一个大文件列表)中保存每个文件的内容,同时保持文件在目录中的顺序。文本不能连接。请看我想要的输出的例子。在

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

我的尝试:

^{pr2}$

输出:

TypeError: Object of type 'TextIOWrapper' is not JSON serializable

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


Tags: 文件of文本目录内容列表顺序example
1条回答
网友
1楼 · 发布于 2024-07-05 14:03:10

您需要将每个文件的文本内容附加到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)

相关问题 更多 >