Answer to Question #345708 in Python for kisara dias

Question #345708

This program allows the user to manage a collection of quotes that is stored in a text file named “data.txt”. Use the “json” module to write data to the text file in JSON format and to read the JSON data from the file back into Python. See Reading 7.1 for details of this. This example data contains the details of three quotes in a list. Each one is a dictionary containing of 4-5 key-value pairs with keys of: • “quote” • “author” • “year” (optional) • “likes” • “loves” The “quote” and “author” keys must contain a quote and its author’s name, however the “year” key/value is only present if the year of the quote is known. 


1
Expert's answer
2022-05-30T08:15:31-0400
import json



data = {"quotes": []}
with open("data.txt") as file:
    lines = file.readlines()
    for line in lines:
        response_list = lines.split(", ")
        quote = response_list[0]
        author = response_list[1]
        if len(response_list) == 5:
            year = response_list[2]
            likes = response_list[3]
            loves = response_list[4]
            data["quotes"].append({
                "quote": quote,
                "author": author,
                "year": year,
                "likes": likes,
                "loves": loves
            })
        else:
            likes = response_list[2]
            loves = response_list[3]
            data["quotes"].append({
                "quote": quote,
                "author": author,
                "likes": likes,
                "loves": loves
            })


with open("result.txt") as outfile:
    json.dump(data, outfile)



with open("result.ttx") as json_file:
    data = json.load(json_file)
    for p in data['quotes']:
        print('Quote: ' + p['quote'])
        print('Author: ' + p['author'])
        if p.get("year", False):
            print('Year: ' + p['year'])
        print("Likes: ", p['likes'])
        print("Loves: ", p["loves"])

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS