Part 08 / Topic 4 of 10
Writing
f.write() writes a string. It does not add a newline, so add "\n" yourself. Numbers must be converted to text first. You can also use print(..., file=f).
Real-world example: write a daily sales report.
sales = {"Tea": 45, "Coffee": 30, "Samosa": 60}
with open("demo_sales.txt", "w", encoding="utf-8") as f:
for item, qty in sales.items():
f.write(f"{item}: {qty}\n")
print("Total:", sum(sales.values()), file=f)
with open("demo_sales.txt", encoding="utf-8") as f:
print(f.read(), end="")
# Tea: 45
# Coffee: 30
# Samosa: 60
# Total: 135
๐ Going deeper:
f.writelines(list_of_strings)writes many strings at once but, despite its name, adds no newlines.print(..., file=f)adds spaces between values and a newline at the end, just like on screen.
Done here? The practice set for Part 8 โ 8 exercises with solutions โ is on the part page.