gpt4 book ai didi

python - 将使用 JSON 数组创建的文件合并到单个文件中

转载 作者:行者123 更新时间:2023-12-01 02:10:20 24 4
gpt4 key购买 nike

为了让您开始,我想将 json 数组文件合并到一个文件中,并在数组末尾附加(逗号)。

MemoryError 现在在我的代码中,请帮助我!

在我的代码中>

import os, sys
path = "censored"
dirs = os.listdir(path)

save_list = []

s = ""
for file in dirs:
save_list.append(file)
for i in range(len(save_list)):
f = open(path + save_list[i], 'r')
s += f.read()
s += s.replace("]", "],")

f.close()
ff = open("a", 'w')
ff.write(s)
ff.close()
print("done")

错误>

Traceback (most recent call last):
File "test.py", line 15, in <module>
s += s.replace("]", "],")
MemoryError

想要结果

file "a" in substance
[{a:b}]
file "b" in substance
[{c:d}]

file "c" want result substance
[{a:b}], [{c:d}]

最佳答案

根据您的代码,您将依次打开每个文件,并且仅关闭最后一个文件。您应该在完成每个文件后打开和关闭它,以提高内存效率。

您实际上可以逐步写入输出文件,而不是将其作为字符串存储在内存中并一次性写入。

实际上没有必要将 dir 中的所有文件保存到 save_list 中并在另一个循环中重新访问它。所以你可以省略save_list

将所有内容放在一起,您将得到以下代码片段:

# everything above as follows

for file in dirs:
curr_file_path = path + file
curr_file_string = ""

# using this would close the file automatically
with open(curr_file_path, 'r') as f:
raw_file = f.read()
curr_file_string = raw_file.replace("]", "],")

# open the output file and set the mode to append ('a') to batch write
# similarly, this will close the output file after every write
with open("output file", "a") as out_f:
out_f.write(curr_file_string)

print("done")

关于python - 将使用 JSON 数组创建的文件合并到单个文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48741383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com