Python Arena
Step 1 of 4

Creating and writing a file

Programs also save data to files: results to keep for later, a report for a person to read, or data for another program to use. Writing uses the same open function as reading, with a second argument, the mode. The mode "w" opens the file for writing:

with open("greeting.txt", "w") as file:
    file.write("Hello, file!\n")
    file.write("This is the second line.\n")

with open("greeting.txt") as file:
    print(file.read())
Output
Hello, file!
This is the second line.
  • open("greeting.txt", "w") creates the file in the program's folder.
  • The file handle's method write writes a string into the file.
  • The second with block opens the file for reading (with no mode, open reads) only to show what the program wrote. On this site, the tests of a task look at the files your program leaves in its folder.

write doesn't add line breaks

print ends each line for you, but write writes exactly the string it gets and nothing more. Line breaks are up to you: end each line with \n. Forget them, and the lines run together:

with open("numbers.txt", "w") as file:
    file.write("one")
    file.write("two\n")
    file.write("three\n")

with open("numbers.txt") as file:
    print(file.read())
Output
onetwo
three

Only strings

write takes exactly one string. Give it a number and Python stops:

points = 42
with open("points.txt", "w") as file:
    file.write(points)
Python stops with
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    file.write(points)
    ~~~~~~~~~~^^^^^^^^
TypeError: write() argument must be str, not int

Turn the number into a string first. An f-string is the handiest way, and it adds the line break at the same time: file.write(f"{points}\n"). It works just as well for a line with several values, such as file.write(f"{name} scored {points}\n").

"w" starts from scratch

If a file with that name already exists, opening it with "w" empties it first. Everything that was in it is gone, without any warning:

with open("status.txt", "w") as file:
    file.write("Version 1\n")

with open("status.txt", "w") as file:
    file.write("Version 2\n")

with open("status.txt") as file:
    print(file.read())
Output
Version 2

That's what you want when a program writes a fresh result every time it runs, but think twice about the name you give open with "w": a typo can wipe out the wrong file.

Your task

Challenge 1 of 3

Fill in the blanks so the program creates the file todo.txt with these two lines in it:

Buy milk
Fix the bike

Challenge 2

Write a program that asks for the user's name and favorite color and saves them to the file profile.txt, as two lines like Name: Ada and Color: green. Then it prints Saved profile.txt.

A run looks like this:

Your name: Ada
Your favorite color: green
Saved profile.txt

and leaves this in profile.txt:

Name: Ada
Color: green

Challenge 3

What does this program print? Type each line it prints.