python - 在Python中将txt文件分割为多个根据其内容命名的文件

标签 python split

我有一个 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/

相关文章:

Python 警告配置不起作用

python - 使用 lxml 从父项中删除 xml 子项

python - 结构错误 : unpack requires a bytes object of length 2 on the second input of the program

javascript - 在找到最长的单词之前拆分字符串

java - Pattern.compile.split 与 StringBuilder 迭代和子字符串

python - NoneType 对象没有属性 endwith (Tensorflow)

python 2.7 - 如何调用父类构造函数

xml - xsl : split and get the X position of param

javascript - 如何在js split中使用特殊文本字符进行正则表达式分割

sql - 使用 split 函数在单独的行中显示每个值