SwadhyAI Notes

All Python notes

Python File Handling 📂

Working with Files

File handling is an essential part of any application. Python uses the built-in open() function to create, read, update, and delete files.

📚 Analogy: The Librarian

Think of File Handling like checking out a book from a library.
- Open (r): You open the book to read it. You can't write in it.
- Write (w): You get a blank notebook. If you write, you start from scratch.
- Append (a): You add a new entry to your diary. You don't erase the past.
- Close: You must return the book when done so others can use it.

✨ The open() Function

The open() function takes two primary parameters: filename and mode.

python
f = open("filename.txt", "r")

🛠️ File Modes

"r" - Read

Default value. Opens a file for reading, error if the file does not exist.

"a" - Append

Opens a file for appending, creates the file if it does not exist.

"w" - Write

Opens a file for writing, creates the file if it does not exist. Overwrites existing content!

"x" - Create

Creates the specified file, returns an error if the file exists.

🎯 Real-World Application: Logging

Most servers use Append ("a") mode to add new events to a log file without deleting old history.

python
import datetime

def log_event(event):
    with open("server.log", "a") as f:
        timestamp = datetime.datetime.now()
        f.write(f"[{timestamp}] {event}\n")

log_event("User logged in")
log_event("Database connection failed")

📝 Text vs Binary

You can also specify if the file should be handled as text or binary mode:

  • "t" - Text - Default. For text files (e.g., .txt, .py).
  • "b" - Binary - Binary mode (e.g., images, audio).

✨ Pro Tip: Context Managers

It is best practice to use the with statement when working with files. It automatically closes the file for you, even if an error occurs.

python
with open("demofile.txt", "r") as f:
    content = f.read()
    print(content)
# File is automatically closed here

⚠️ Encoding

When working with text files, it is recommended to specify the encoding to avoid issues with special characters.

python
f = open("demofile.txt", "r", encoding="utf-8")