So far, everything we’ve done exists only inside the program.
But what if your program could remember things even after it closes?
That’s where file handling comes in.
So far, we’ve worked with variables, functions, and modules.
But in real applications, data doesn’t just disappear when a program stops running.
It is saved in files like .txt, .csv, or databases.
Python allows us to work with these files using file handling.
🔹 Opening a File
To work with a file, we first open it using open().
file = open("file.txt", "r")
The "r" means read mode (we are only reading the file).
🔹 Reading a File
Once the file is open, we can read its content.
file = open("file.txt", "r")
content = file.read()
print(content)
file.close()
Always remember to close the file after using it.
🔹 Writing to a File
We can also create or write into files using "w" mode.
file = open("file.txt", "w")
file.write("Hello, this is my first file.")
file.close()
⚠️ Note: Writing mode will overwrite existing content.
🔹 Appending to a File
If you don’t want to overwrite, use "a" mode.
file = open("file.txt", "a")
file.write("\nThis is an additional line.")
file.close()
This adds new content without deleting old data.
💡 Why File Handling Matters
File handling allows your programs to:
- Save user data
- Store results
- Keep records
- Work like real applications Without it, everything resets once the program stops. With it, your program can actually remember things.
🌱 Challenge
Create a program that:
- Writes your name and age into a file
- Opens the file again
- Reads and prints the content Try also appending a new line after that.
Next, we’ll explore exception handling, where your program learns how to handle errors without crashing.
Top comments (0)