【问题标题】:split txt file to multiple files named according to their contents in Python将 txt 文件拆分为多个文件,根据它们在 Python 中的内容命名
【发布时间】:2013-02-13 17:01:58
【问题描述】:

我有一个 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 文件必须根据“名称”属性命名,因此该示例文件将命名为“任意名称 1.txt”。

对此的任何帮助将不胜感激。我可以使用 bash 拆分文件,但这不允许我需要的命名。

我希望有人可以帮助我找到一个 Python 解决方案,它也可以正确命名文件。

提前致谢

【问题讨论】:

  • 如果您可以解析整个文件,这很简单;那么它只是外部 JSON 列表部分的循环。你试过什么?

标签: python split


【解决方案1】:
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 之后没有排序,但应该正确拆分。

【讨论】:

  • 感谢您,效果很好。不幸的是,生成的 json 文件的顺序是一个问题。您是否知道以任何方式维护原始文件中的订单?再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 2013-01-09
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2021-08-02
相关资源
最近更新 更多