Lesson: File Handling in Python
Lesson: File Handling in Python
[introduction]
Welcome back! Today we’ll learn about file handling, which allows Python programs to read from and write to files. This is essential for saving data, loading data, creating logs, and interacting with the real world outside your program.
By the end of this lesson, you’ll understand how to open, read, write, append, and safely manage files.
[concept_explanation]
File handling in Python revolves around the built-in open() function.
The general pattern is:
But the recommended modern way is using a with-statement, which automatically closes the file:
Common File Modes
| Mode | Meaning |
|---|---|
"r" | Read (default) |
"w" | Write (overwrites file) |
"a" | Append (adds to file) |
"x" | Create (fails if file exists) |
"b" | Binary mode |
"t" | Text mode (default) |
[python_examples]
1. Reading a file
2. Reading line by line
3. Writing to a file (overwrites)
4. Appending to a file
5. Writing multiple lines
[analogy]
Think of a file like a notebook:
-
"r"mode is like opening it to read what’s already written. -
"w"mode is like starting a new notebook from scratch. -
"a"mode is like adding more notes at the end of your notebook. -
The with-statement is like automatically closing the notebook when you're done.
[practice_task]
Try doing the following:
-
Create a file named
"my_info.txt"using"w"mode. -
Write your name and one hobby into it.
-
Reopen the file in
"a"mode and add another hobby. -
Reopen the file in
"r"mode and print all contents.
[quiz]
-
What does the
"w"mode do? -
Why is using
with open(...)recommended? -
What will this code do?
-
True or False:
"r"mode will create a new file if it doesn’t exist.
[common_mistakes]
-
Forgetting to close files (fixed by using
with) -
Using
"w"when you meant"a"→ accidentally deleting the file -
Trying to read a file that does not exist
-
Forgetting newline characters (
\n) when writing multiple lines -
Mixing up text and binary modes
[extra_notes]
-
Binary mode
"rb"and"wb"is used for images, PDFs, etc. -
You can check if a file exists using
os.path.exists(). -
Error handling with
try/exceptis useful for file operations. -
File handling is a crucial skill for working with data science, logs, and configuration files.
Comments
Post a Comment