save_file() Works in Python (Beginner-Friendly)When building apps, we often need to save data from Python objects into a file.
Convert Python data like:
{
"Eric": Person object,
"Emily": Person object
}
into text like:
Eric;123;456;ADDRESS:Turku
Emily;789;ADDRESS:Helsinki
def save_file(self, phonebook: dict):
with open(self.__filename, "w") as f:
for name, person in phonebook.items():
line = [name]
line += person.numbers()
if person.address():
line.append("ADDRESS:" + person.address())
f.write(";".join(line) + "\n")
with open(self.__filename, "w") as f:
“w” means write mode:
for name, person in phonebook.items():
Example:
name = "Eric"
line = [name]
Result:
["Eric"]
line += person.numbers()
Becomes:
["Eric", "123", "456"]
line.append("ADDRESS:" + person.address())
Becomes:
["Eric", "123", "456", "ADDRESS:Turku"]
f.write(";".join(line) + "\n")
Result:
Eric;123;456;ADDRESS:Turku
save_file() converts Python objects into text lines and stores them in a file.
