我在目录中有数千个文本文件,并且希望将每个文件的内容保存在列表(一个大文件列表)中,同时保持文件在目录中的顺序。这些文本不应该连接在一起。请参阅我想要的输出示例。
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格式串行转储文本文件的任何想法都将不胜感激。
答案 0 :(得分: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)