Reputation: 41
I have a large .txt file in JSON format which leads on as follows:
{
"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",
},
and so on, for 2000 entries.
What I am trying to do is split this file into individual .txt files, while retaining the JSON formatting.
So, in essence, I need to split the file after the }, to make 2000 new .txt files as follows:
{
"Name": "arbitrary name 1",
"Detail 1": "text here",
"Detail 2": "text here",
"Detail 3": "text here",
}
Furthermore, these 2000 new .txt files must be named according to the "Name" attribute, so this example file would be named "arbitrary name 1.txt".
Any help with this would be greatly appreciated. I am able to split the file using bash, but this doesn't allow for the naming that I need.
I am hoping someone can help me find a Python solution that can also name the files correctly.
Thanks in advance
Upvotes: 2
Views: 663
Reputation: 425
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))
Be aware that the result json is not sorted afterwards but it should be properly splitted.
Upvotes: 2