我有一个 JSON 格式的大型 .txt 文件,其结果如下:
{
"Name": "arbitrary name 1",
"Detail 1": "text here",
"Detail 2": "text here",
"Detail 3": "text here",
},
{
"Name": "arbitrary name 1",
"Detail 1": "text here",
"Detail 2": "text here",
"Detail 3": "text here",
},
依此类推,共 2000 个条目。
我想要做的就是将此文件拆分为单独的 .txt 文件,同时保留 JSON 格式。
因此,本质上,我需要在 } 之后拆分文件,以生成 2000 个新的 .txt 文件,如下所示:
{
"Name": "arbitrary name 1",
"Detail 1": "text here",
"Detail 2": "text here",
"Detail 3": "text here",
}
此外,这 2000 个新的 .txt 文件必须根据“Name”属性命名,因此此示例文件将命名为“任意名称 1.txt”。
对此的任何帮助将不胜感激。我可以使用 bash 拆分文件,但这不允许我需要的命名。
我希望有人能帮我找到一个可以正确命名文件的 Python 解决方案。
提前致谢
最佳答案
import json
with open('file.txt', 'r') as f:
data = json.loads(f.read())
for line in data:
with open(line['Name'] + '.txt', 'w') as f:
f.write(json.dumps(line))
请注意,结果 json 之后不会排序,但应该正确拆分。
关于python - 在Python中将txt文件分割为多个根据其内容命名的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14858879/