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:

file = open("filename", "mode") # work with the file file.close()

But the recommended modern way is using a with-statement, which automatically closes the file:

with open("filename", "mode") as file: # work with the file

Common File Modes

ModeMeaning
"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

with open("example.txt", "r") as f: content = f.read() print(content)

2. Reading line by line

with open("example.txt", "r") as f: for line in f: print(line.strip())

3. Writing to a file (overwrites)

with open("notes.txt", "w") as f: f.write("Hello, this is a new file!")

4. Appending to a file

with open("notes.txt", "a") as f: f.write("\nThis line is added later.")

5. Writing multiple lines

lines = ["apple\n", "banana\n", "cherry\n"] with open("fruits.txt", "w") as f: f.writelines(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:

  1. Create a file named "my_info.txt" using "w" mode.

  2. Write your name and one hobby into it.

  3. Reopen the file in "a" mode and add another hobby.

  4. Reopen the file in "r" mode and print all contents.


[quiz]

  1. What does the "w" mode do?

  2. Why is using with open(...) recommended?

  3. What will this code do?

with open("data.txt", "a") as f: f.write("Hello\n")
  1. 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/except is useful for file operations.

  • File handling is a crucial skill for working with data science, logs, and configuration files.

Comments

Popular posts from this blog

Ecommerce website

Yes, Python is an object-oriented programming (OOP) language, but it is also a multi-paradigm language

Your task is to find the missing number.