Read and Write Text 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:
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 Python!")
writes the message to that file.
This is useful when you need to store information to use later, like saving results or logs.
Read from a file
Now read what you just wrote:
with open("message.txt", "w") as file:file.write("Hello from Python!")with open("message.txt", "r") as file:content = file.read()print(content)
We just made Python read from a real file! ...