1. Write a file

A file stores text outside your variables. These exercises run in an isolated virtual filesystem: the files live only while the Python session runs and disappear when you reload the page. /tmp is a folder inside that virtual filesystem, not a real folder on your computer.

open() is a built-in function that opens a file and returns a file object. Its common signature is:

  • file — a string with the path of the file to open, such as "/tmp/notes.txt". Here the name means the path, not the file object that open() returns.
  • mode — a string that says what you want to do with the file. Default: "r" (read).

The real open() has more optional parameters, including encoding. These exercises use the defaults. You can inspect them with help(open).

The modes you need in this chapter:

  • "r" — read. The file must already exist.
  • "w" — write. Creates the file, or empties it if it already exists.
  • "a" — append. Adds text at the end; creates the file if it does not exist.

The file object has methods:

  • write(text) writes exactly the string you pass. It does not add a newline, so write "\n" yourself when you want one.
  • close() takes no arguments. Call it when you finish, or let with close the file for you (lesson 3 of this chapter).

After this code, /tmp/demo.txt contains the text Hello followed by a newline.

Coming from JavaScript? Calling open() with "w" is similar to fs.writeFileSync: it creates or replaces the file. In Python you write through the returned file object and then call close().

#01

Write your first line

Calling open() with "w" creates the file or empties it. The returned file object has a write(text) method, and close() releases it.

Open /tmp/notes.txt in "w" mode, write Hello, file! followed by a newline, and close the file. Then print Saved.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Count the characters written

write(text) returns the number of characters it wrote. It does not add a newline.

Open /tmp/count.txt in "w" mode. Store the result of writing Python in a variable, close the file, and print that result.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Append a line

Mode "a" adds text at the end of an existing file. It creates the file if it does not exist yet.

First open /tmp/log.txt in "w" mode, write First line followed by a newline, and close it. Then open the same path in "a" mode, write Second line followed by a newline, and close it. Finally print Appended.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Overwrite a file

Opening an existing file in "w" mode empties it before you write, so the old content is lost.

Open /tmp/overwrite.txt in "w" mode, write old, and close it. Open the same path again in "w" mode, write new, and close it. Then print Replaced.

Print exactly:

Create a free account to save your progress and unlock chapter 2.