...

/

Talk to Files

Talk to Files

Learn how to read from and write to text files.

You’ve created data in Python—now let’s save it and read it back later. Time to give Python long-term memory using files!

Write to a file

Try this:

Press + to interact
Python
with open("message.txt", "w") as file:
file.write("Hello from Python!")

You won’t see any output on the screen after running this code, and that’s normal! This code is writing the message “Hello from Python!” into a file called message.txt.

The with open("message.txt", "w") part tells Python to open a file named message.txt in “write” mode ("w"). If the file doesn’t already exist, Python will create it for you. Once the file is open, file.write("Hello from ...