Syllabus Lesson 38 of 239 · Files, Errors & Modules
Files, Errors & Modules

Reading and Writing Text Files

Your programs can save data to disk and read it back later. Python opens a file with open(path, mode). The two modes you need first are "w" (write, which creates or overwrites the file) and "r" (read).

The safe way to work with files is the with-statement, also called a context manager. It opens the file, hands it to you, and closes it automatically when the block ends, even if something goes wrong.

with open("greeting.txt", "w") as f:
    f.write("Hello\n")
    f.write("World\n")

with open("greeting.txt", "r") as f:
    text = f.read()

print(text)

For real-world text and CSV work, pass encoding="utf-8" when you open a file, for example open("notes.txt", "w", encoding="utf-8"). It keeps accented characters and symbols readable and avoids a UnicodeDecodeError or mismatched text when your code runs on another operating system.

f.write() does not add a newline for you, so include \n yourself when you want separate lines. To read the whole file as one string use f.read(). To read it as a list of lines use f.readlines(), or loop directly:

with open("greeting.txt", "r") as f:
    for line in f:
        print(line.strip())

Note: here you must create the file first in the same snippet, because the grader starts with an empty filesystem.

Your turn

Write the three lines apples, bananas and cherries (one per line) to a file called notes.txt, then open it again and read the whole thing into a variable named content. Finally print(content).

Spotted a problem in this lesson? Report it

Code · runs in your browser
Output