✦ Python Foundations Working with Data module

Concept 20 · Working with Files

Save and read text.
Use a temporary browser file.

A text file stores characters. Use with open(...) so Python closes the file automatically; use "w" to write and "r" to read.

01 Learn02 Try03 Predict

with open() safely reads and writes a text file.

A text file stores characters. Use with open(...) so Python closes the file automatically; use "w" to write and "r" to read.

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Learning Python is fun!")

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)

This playground creates notes.txt before reading it. The file lives only in the browser Python environment and is not a file on your computer.

Learning Python is fun!

Change one value, then explain how the resulting data changes.

↳

Keep this in mind: Follow each data operation in order before predicting the result.

Try it
with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Learning Python is fun!")

with open("notes.txt", "r", encoding="utf-8") as file:
    content = file.read()

print(content)
# Change the text, then run this complete example again

Run the example, then change one value and observe the result.

Python Playground

Loading Python runtime…

Edit the example and run it in your browser.

working_with_files.pyPython
OutputWaiting for Python
The browser runtime is loading. You can still edit the example code.

Pyodide runs Python in a browser Web Worker. It is stopped and restarted if code keeps running. Browser execution is not a complete security boundary; do not enter secrets or rely on it for untrusted code isolation.

What will this program print?

Read each data operation before choosing an answer.

with open("todo.txt", "w", encoding="utf-8") as file:
    file.write("Read\nPractice")

with open("todo.txt", "r", encoding="utf-8") as file:
    print(file.read())
Choose the output
Sloby, the Python AI Tutor mascot

Your learning mentor

Ask Sloby about working with files

Describe what feels unclear and Sloby will guide your reasoning.

Hi! I'm Sloby. Let's read and write a temporary Python text file.

What will this program print, and why is with open(...) useful when working with a text file?

with open("message.txt", "w", encoding="utf-8") as file:
    file.write("Hello file")

with open("message.txt", "r", encoding="utf-8") as file:
    text = file.read()

print(text.upper())
Python AI Tutor · Learn by understanding, not just by running code.