Exercises
Read Files
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Read the file a line at a time and print each name without its newline.
Python
with open("names.txt", "w", encoding="utf-8") as f:
f.write("Ada\nGrace\n")
# loop over the file
Looping over the file object gives one line at a time.
with open("names.txt", "w", encoding="utf-8") as f:
f.write("Ada\nGrace\n")
with open("names.txt", encoding="utf-8") as f:
for line in f:
print(line.strip())Exercise 2Passed
Number the lines from 1 as you print them.
Python
with open("names.txt", "w", encoding="utf-8") as f:
f.write("Ada\nGrace\n")
# print '1 Ada' and '2 Grace'
enumerate takes a start argument.
with open("names.txt", "w", encoding="utf-8") as f:
f.write("Ada\nGrace\n")
with open("names.txt", encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.strip())Exercise 3Passed
Split each row on the comma and print the name and year separately.
Python
with open("people.txt", "w", encoding="utf-8") as f:
f.write("Ada,1815\nGrace,1906\n")
# print 'Ada was born in 1815' and so on
strip() first, then split(",").
with open("people.txt", "w", encoding="utf-8") as f:
f.write("Ada,1815\nGrace,1906\n")
with open("people.txt", encoding="utf-8") as f:
for line in f:
name, year = line.strip().split(",")
print(f"{name} was born in {year}")