Lesson ยท 18 min
Write files
From answers to files
Until now, your results stayed in variables, or you printed them. Other people need a file: a CSV file that a spreadsheet program opens, or a short text report.
Write text
open takes a second argument, the mode.
| Mode | Meaning |
|---|---|
"r" |
Read. This is the default. |
"w" |
Write. Python makes the file. If the file exists, Python empties it first. |
"a" |
Append. Python adds the new text to the end of the file. |
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("First line\n")
file.write("Second line\n")
write takes one text, and it does not end the line. You add \n yourself.
Be careful with the mode "w". It deletes the old content of the file, and it does not ask.
Write a CSV file
csv.writer does the reverse of csv.reader. Its method writerow takes a list of values and writes one row. It puts quotation marks around a value that has a comma in it.
import csv
with open("pets.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["name", "age"])
writer.writerow(["Biscuit", 4])
newline="" is important here. Without it, the file gets an empty line after each row on some computers.
csv.DictWriter writes dictionaries. You give it the names of the columns.
pets = [{"name": "Biscuit", "age": 4}, {"name": "Pepper", "age": 2}]
with open("pets.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age"])
writer.writeheader()
writer.writerows(pets)
list(pets[0].keys()) gives the names of the columns from the first row.
Columns in a text report
A person reads a text report, so the columns must line up. An f-string can give a value a fixed width. Write a colon after the value, and then the form.
print(f"[{'Old Mill':<12}]") # [Old Mill ]
print(f"[{42:>6}]") # [ 42]
print(f"[{3.14159:>8.2f}]") # [ 3.14]
<12puts the value to the left, in 12 characters.>6puts the value to the right, in 6 characters.>8.2fputs a number to the right, in 8 characters, with 2 digits after the decimal point.
Text usually goes to the left, and numbers go to the right.
Look at a file that you wrote
In this editor, a file that your code writes exists only while the code runs. It has no tab. To look at the file, read it at the end of your code, and print the text.
with open("notes.txt", encoding="utf-8") as file:
print(file.read())
On your own computer, the file stays in the folder of your program.
Your turn
main.py loads 18 trips, and it makes the list ranked. Each item of ranked is a pair: the name of a start station, and its number of trips. Do the tasks in order.
Tasks
5 to do
Task 1, not checked yet. Write the file
summary.csvwithcsv.writer. The first row is the header:stationandtrips. Then write one row for each pair inranked: the name and the number.Task 2, not checked yet. Write a function
format_line(name, count, share). It returns one line of a report:nameto the left in 14 characters,countto the right in 5 characters,shareto the right in 7 characters with 1 digit after the decimal point, and then%.format_line("Old Mill", 1, 5.56)returns"Old Mill 1 5.6%".Task 3, not checked yet. Write the file
report.txt. The first line isTrips by start station. Then write one line for each pair inranked, made withformat_line. The share is the percent of all trips. The last line is the total:format_line("Total", total, 100), wheretotalis the number of trips.Task 4, not checked yet. Add the line
Source: trips.csvto the end ofreport.txt. Open the file again in the mode"a", so that the other lines stay in the file.Task 5, not checked yet. Write a function
save_rows(file_name, rows).rowsis a list of dictionaries that all have the same keys. The function writes them as a CSV file with a header row. Usecsv.DictWriter.
Task 1 of 5
Write the file summary.csv with csv.writer. The first row is the header: station and trips. Then write one row for each pair in ranked: the name and the number.