0

I have been dealing with a little problem while programming python database. If I make new entry it will stay in the line with previous and I dont know where should I add \n or how could I make it in second line. Thanks for help. These are lines we are dealing with. #edit: using import json I am new to asking on stackoverflow, I dont think there are more data needed but if I made mistake I will place rest of code

def write_to_file(data):
    with open('database.txt', 'w') as outfile:
        json.dump(data, outfile)

def read_from_file():
    with open('database.txt', 'r') as infile:
        return json.load(infile)

def add_entry(first, second, third, fourth, fifth, sixth, seventh, eighth, ninth):
    data = read_from_file()
    data.append({'id': first , 'titul': second, 'meno': third, 'priezvisko': fourth, 'ulica a cislo': fifth, 'mesto': sixth, 'psc': seventh, 'tlc': eighth, 'email': ninth})
    write_to_file(data)

I tried adding \n to nearly every part of the code but nothing helped

eccentricOrange
  • 876
  • 5
  • 18
  • Sorry I am kinda new to this here is rest: def write_to_file(data): with open('database.txt', 'w') as outfile: json.dump(data, outfile) def read_from_file(): with open('database.txt', 'r') as infile: return json.load(infile) – Tomáš Répáš Jan 26 '23 at 09:56
  • You mean you are implementing a SQL db from scratch? – Gameplay Jan 26 '23 at 09:57
  • I updated it sorry – Tomáš Répáš Jan 26 '23 at 09:58
  • @Gameplay the term "database" also has a much broader, more informal meaning. – Karl Knechtel Jan 27 '23 at 04:55
  • Welcome to Stack Overflow. "If I make new entry it will stay in the line with previous and I dont know where should I add \n or how could I make it in second line." I'm not sure I understand the question. **Why is this a problem**? When you tried the code, you were *able to load* the data again correctly, after saving it, right? So why does it matter what the file looks like? That said, given that the goal is to make the file look a certain way, this is a common question that has an extremely well established Q&A (the linked duplicate has more than 2 million views). – Karl Knechtel Jan 27 '23 at 04:56

1 Answers1

0

Whitespace (i.e., spaces, lines, tabs etc) doesn't matter in the JSON format. So, for compactness, the JSON module dumps to the file as one condensed chunk of text. This is a feature for many applications (like web services) where transmitting/storing a lower amount of data is valuable.

You could specify something like indent=4 to better format the text.

def write_to_file(data):
    with open('database.txt', 'w') as outfile:
        json.dump(data, outfile, indent=4)
eccentricOrange
  • 876
  • 5
  • 18