Home > Blockchain >  Create and append text file using python dictionary
Create and append text file using python dictionary

Time:05-12

In the initial stage, I tried the following code. This code I used to create text file using the python

import json
final_key = ["letters", "words", "score"]
final_list = []
letters_1=['U', 'I', 'J', 'T', 'D', 'F', 'S', 'H', 'J']
final_list.append(letters_1)
word=['U', 'T', 'S']
final_list.append(word)
score = 3
final_list.append(score)
res = {}
for key in final_key:
    for value in final_list:
        res[key] = value
        final_list.remove(value)
        break
with open('log.txt', 'w') as convert_file:
     convert_file.write(json.dumps(res))
final_list_1=[]
letters_2=['A', 'P', 'J', 'P', 'F', 'F', 'L', 'H', 'P']
final_list_1.append(letters_2)
word_1=['L', 'V', 'S','G']
final_list_1.append(word_1)
score_1 = 10
final_list_1.append(score_1)
res_1 = {}
for key in final_key:
    for value in final_list_1:
        res_1[key] = value
        final_list_1.remove(value)
        break
with open('log.txt', 'a') as convert_file:
     convert_file.write(json.dumps(res_1)) 

my result

{"letters": ["U", "I", "J", "T", "D", "F", "S", "H", "J"], "words": ["U", "T", "S"], "score": 3}
{"letters": ["A", "P", "J", "P", "F", "F", "L", "H", "P"], "words": ["L", "V", "S", "G"], "score": 10}

Now, I want to create that text file with the following output

{
"log": [
        {
          "letters": ["U", "I", "J", "T", "D", "F", "S", "H", "J"], 
          "words": ["U", "T", "S"], 
          "score": 3
        },
        {
          "letters": ["A", "P", "J", "P", "F", "F", "L", "H", "P"], 
          "words": ["L", "V", "S", "G"], 
          "score": 10
        }
        ]
}

How can I change the code to achieve above task

Thank you !!!

CodePudding user response:

You can't do two separate writes. A JSON file needs to be a single object.

import json

final_list = []
row = {
    'letters': ['U', 'I', 'J', 'T', 'D', 'F', 'S', 'H', 'J'],
    'words': ['U', 'T', 'S'],
    'score': 3
}
final_list.append(row)

row = {
    'letters': ['A', 'P', 'J', 'P', 'F', 'F', 'L', 'H', 'P'],
    'word': ['L', 'V', 'S','G'],
    'score': 10
}
final_list.append(row)

with open('log.txt', 'w') as convert_file:
    json.dump({"log": final_list}), convert_file)

CodePudding user response:

That's an awful lot of code for something so trivial. Try this:

import json

letters = [['U', 'I', 'J', 'T', 'D', 'F', 'S', 'H', 'J'], ['A', 'P', 'J', 'P', 'F', 'F', 'L', 'H', 'P']]
words = [['U', 'T', 'S'], ['L', 'V', 'S','G']]
scores = [3, 10]

log = []

for letter, word, score in zip(letters, words, scores):
    log.append({'letters': letter, 'words': word, 'score': score})

with open('log.txt', 'w') as logfile:
    logfile.write(json.dumps({'logs': log}, indent=4))
  • Related