Chapter 7: File Operations / Lesson 41

File Handling

Introduction to File Handling

File handling allows you to read from and write to files on your computer. This is essential for storing data persistently, reading configuration files, processing data files, and much more. Python provides built-in functions and methods to work with files easily.

Understanding file handling is crucial for building real-world applications that need to save and load data.

Opening Files

To work with a file, you first need to open it using the open() function. The function takes a file path and a mode (read, write, append, etc.):

opening_files.py
# Open file for reading file = open("example.txt", "r") # Open file for writing file = open("example.txt", "w") # Open file for appending file = open("example.txt", "a") # Always close the file when done file.close() # Better: use with statement (automatically closes) with open("example.txt", "r") as file: # File operations here pass # File automatically closed

File Modes

Python supports various file modes for different operations:

  • "r" - Read mode (default, file must exist)
  • "w" - Write mode (creates file if doesn't exist, overwrites if exists)
  • "a" - Append mode (adds to end of file)
  • "x" - Exclusive creation (fails if file exists)
  • "r+" - Read and write mode
  • "b" - Binary mode (for images, videos, etc.)

The with Statement

The with statement is the recommended way to work with files. It automatically handles closing the file, even if an error occurs:

with_statement.py
# Using with statement (recommended) with open("data.txt", "r") as file: content = file.read() print(content) # File is automatically closed here # Without with statement (must manually close) file = open("data.txt", "r") content = file.read() file.close() # Don't forget this! # The with statement is safer because: # 1. File is always closed, even if error occurs # 2. More readable and Pythonic # 3. Prevents resource leaks

File Paths

You can work with files using relative or absolute paths:

file_paths.py
# Relative path (from current directory) with open("data.txt", "r") as file: pass # Path in subdirectory with open("folder/data.txt", "r") as file: pass # Absolute path (full path from root) with open("/Users/username/documents/data.txt", "r") as file: pass # Using os.path for cross-platform compatibility import os path = os.path.join("folder", "data.txt") with open(path, "r") as file: pass

Best Practices

✅ File Handling Tips

• Always use the with statement when possible

• Close files explicitly if not using with

• Handle file errors (we'll learn this in error handling lesson)

• Use appropriate file modes for your needs

• Be careful with write mode - it overwrites existing files!

🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...