Talk to Files
Explore how to give Python long-term memory by writing, reading, and appending to files. Understand how to use file modes and string concatenation to store and manage data effectively in Python programs.
We'll cover the following...
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:
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:
We just made Python read from a real file!
Append more content
Want to add to the file instead of replacing it?
Use mode "a" (append). Run the read code—we’ll see both lines now:
Remember: When using
"w", the file is replaced with new content each time. Use"a"(append mode) if you want to add new content without removing anything already in the file.For example, if you're logging scores or writing diary entries, you don’t want to overwrite the old entries each time you write. That’s why you use
"a"when you want to add more content, not replace it.
Your turn: Write your diary
Let's look at the code below that prompts the user for a diary entry and appends it to a file named diary.txt. The with open statement to handles the file operations, ensuring the file is properly closed after writing.
entry = input("Write a diary entry: ")
with open("diary.txt", "a") as file:
file.write(entry + "\n")
Note: After you run the code and type your diary entry, it gets saved to a file called
diary.txtin the current directory (/usercode).To check and read your saved entry:
In the terminal below, type
lsThis lists all files. You should see
diary.txtthere.
Then type
cat diary.txtand press “Enter.”This will show your saved diary entries!
Add a new entry every time you run it!
Concatenation in Python
Concatenation in programming means combining or joining multiple pieces of data (usually strings) into a single string. We use the + operator for this.
For example:
If you have two strings:
"Hello"and"World", concatenating them would result in"HelloWorld".You can also add spaces, punctuation, or any other characters between them.
Note: The
+operator is used to concatenate (or join) different pieces of text together in Python. In the code above, the+operator is being used to combine the user's input with a newline character ("\n") to ensure each diary entry starts on a new line in the file.
Why use with
withautomatically opens and closes the file for us.It prevents errors and makes our code cleaner.