用Python将txt文件按内容分割为多个文件

2 投票
1 回答
655 浏览
提问于 2025-04-17 15:46

我有一个很大的 .txt 文件,里面是 JSON 格式的,开头是这样的:

{
    "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" 属性来命名,所以这个示例文件会被命名为 "arbitrary name 1.txt"。

如果有人能帮我解决这个问题,我会非常感激。我可以用 bash 拆分文件,但这样无法满足我对命名的需求。

我希望有人能帮我找到一个 Python 的解决方案,这样也能正确命名文件。

提前谢谢大家!

1 个回答

2
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数据在之后不会被排序,但它应该被正确地分开。

撰写回答