Chapters
Python114 chapters

Exercises

Read Files

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

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
Exercise 2

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'
Exercise 3

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