Let’s start Python Programming for Beginners to advanced. File Handling, Lectures 12
π Lecture 12: File Handling
π― Goal
By the end of this lecture, you will:
- Understand how to read from and write to files in Python.
- Be able to use
open()
,read()
,write()
, andwith
statements. - Practice saving game data, logs, or user info to a file.
- Build a simple program that saves and loads text.
π§ What Is File Handling?
So far, all the data weβve worked with disappears when the program ends.
File handling lets us save data permanently on our computer, like saving a game, keeping a log, or storing notes.
π Think of it like writing in a notebook:
- Writing β Saving to a file
- Reading β Loading from a file
π Opening Files with open()
To work with a file, we use the open()
function.
Syntax:
file = open("filename.txt", "mode")
The mode tells Python what we want to do:
Mode | Meaning |
---|---|
"r" | Read (file must exist) |
"w" | Append (adds to the end of file) |
"a" | Append (adds to the end of the file) |
"r+" | Read and write |
πΎ Writing to a File
Letβs create a file and write some text into it.
Example:
file = open("message.txt", "w")
file.write("Hello, world!")
file.close()
This creates a file called message.txt
and writes "Hello, world!"
inside.
π Note: If the file already exists,
"w"
will overwrite it.
π Reading from a File
Now let’s read what’s inside that file.
Example:
file = open("message.txt", "r")
content = file.read()
print(content)
file.close()
π Output:
Hello, world!

π‘οΈ Better Way: Using with
Statement
Using with
is safer and cleaner because it automatically closes the file for you.
Writing with with
:
with open("log.txt", "w") as f:
f.write("Game started\n")
f.write("Player name: Alice")
Reading with with
:
with open("log.txt", "r") as f:
print(f.read())
β Appending to a File
Use "a"
mode to add more text without deleting what’s already there.
with open("log.txt", "a") as f:
f.write("\nGame ended")
Now log.txt
will have:
Game started
Player name: Alice
Game ended
π Reading Line by Line
Sometimes, you want to read one line at a time.
Example:
with open("log.txt", "r") as f:
for line in f:
print("Line:", line.strip())
.strip()
removes extra spaces or newline characters.
π§ͺ Try It Yourself!
Write a program that:
- Asks the user to enter a message.
- Saves it to a file called
user_message.txt
. - Then reads and prints the message back.
π‘ Sample Code:
msg = input("Enter a message: ")
# Save to file
with open("user_message.txt", "w") as f:
f.write(msg)
# Read from file
with open("user_message.txt", "r") as f:
print("You saved:", f.read())
π Challenge (Optional)
Make a simple diary app where the user can:
- Add an entry (appended to a file).
- View all entries (read from the file).
Example:
while True:
action = input("What do you want to do? (add/view/quit): ").lower()
if action == "add":
entry = input("Write your diary entry: ")
with open("diary.txt", "a") as f:
f.write(entry + "\n---\n")
elif action == "view":
try:
with open("diary.txt", "r") as f:
print(f.read())
except FileNotFoundError:
print("No diary entries yet.")
elif action == "quit":
print("Goodbye!")
break
else:
print("Invalid choice.")
π§ Kids Corner
π§ Imagine your robot has a notebook where it remembers everything you say.
Every time you talk, it writes it down β and when you ask, it reads it back to you!
π€ Robot says:
I remember what you told me yesterday!
π Summary
- I used
open()
to work with files. - Use
"w"
,"r"
,"a"
modes to write, read, or append. - Always close files, or better yet, use the
with
statement. - You can build useful tools like diaries, logs, game saves, and more!
Stay Updated
If you found this information useful, donβt forget to bookmark this page and Share and leave your feedback in the comment section below.
Python Programming For Beginners To Advanced