File Handling - Reading and Writing Files
File handling is like having a notebook. You can read from it (reading files), write new notes in it (writing files), or add more notes at the end (appending files). Python helps you manage these notebooks on your computer.
File handling allows your Python programs to store data **permanently** – even after the program ends. Without files, all data disappears when the program stops. With files, you can save user preferences, game scores, log entries, or any other data to your computer's storage and retrieve it later.
**Opening a file:**
Use the `open()` function. It returns a file object.
```python
file = open("filename.txt", "mode")
```
**File modes (the second argument):**
- `"r"` – **Read** (default). Opens file for reading. Error if file does not exist.
- `"w"` – **Write**. Opens file for writing. Creates new file or **overwrites** existing content.
- `"a"` – **Append**. Opens file for writing. Adds new content to the **end** of the file (preserves existing content).
- `"x"` – **Exclusive creation**. Fails if file already exists.
- `"b"` – **Binary mode** (e.g., `"rb"` for reading binary files like images).
- `"t"` – **Text mode** (default).
**Reading files:**
- `.read()` – reads the entire file as a single string.
- `.readline()` – reads one line at a time (including newline).
- `.readlines()` – returns a list of all lines (each with newline).
**Writing files:**
- `.write(string)` – writes a string to the file (does not automatically add newline).
- `.writelines(list)` – writes a list of strings to the file.
**Closing files (critical!):**
Files must be closed to free system resources and ensure data is saved.
```python
file.close()
```
If you forget to close, data may be lost or the file may remain locked.
**The `with` statement (recommended):**
`with` automatically closes the file, even if an error occurs. This is the **best practice**.
```python
with open("file.txt", "r") as file:
content = file.read()
# file is automatically closed here
```
**File paths:**
- **Relative path** – relative to the current working directory (e.g., `"data/input.txt"`).
- **Absolute path** – full path from root (e.g., `"/home/user/data.txt"` on Linux/Mac, `"C:\\Users\\name\\file.txt"` on Windows).
Use forward slashes `/` for cross‑platform compatibility, or double backslashes `\\` on Windows.
**Checking if a file exists:**
Use `os.path.exists()` from the `os` module.
```python
import os
if os.path.exists("myfile.txt"):
with open("myfile.txt", "r") as f:
data = f.read()
```
**Working with CSV files (comma‑separated values):**
CSV is a common format for spreadsheets and data exchange. You can read/write manually with `.split(',')` or use the `csv` module.
```python
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age"])
```
**Common mistakes:**
- Forgetting to close the file (use `with` to avoid).
- Using `"w"` mode when you meant `"a"` – overwrites existing data.
- Reading a file that doesn't exist without checking – causes `FileNotFoundError`.
- Assuming `.write()` adds a newline – you must add `\n` manually.
- Mixing forward and backslashes in paths on Windows.
**Real‑world applications:**
- Saving user settings or high scores.
- Logging errors or program activity.
- Reading configuration files (e.g., `.ini`, `.json`, `.yaml`).
- Processing large datasets line by line (memory efficient).
- Exporting reports as CSV for Excel.
**Practice exercises:**
1. Write a program that saves a user's name and favorite color to a file, then reads it back and displays it.
2. Create a to‑do list: allow the user to add tasks and save them to a file; on next run, load and display existing tasks.
3. Write a program that counts how many words are in a text file.
4. Copy the contents of one file to another.
5. Read a CSV file of student grades and calculate the average score.
**Example with error handling:**
```python
try:
with open("data.txt", "r") as f:
content = f.read()
except FileNotFoundError:
print("File not found. Creating a new one.")
with open("data.txt", "w") as f:
f.write("Initial content")
```
# ========== EXAMPLE 1: Writing to a File (w mode) and Reading it Back ==========
print("=== Example 1: Write and Read a Text File ===")
# Write to a file (overwrites if exists)
with open("diary.txt", "w") as file:
file.write("My Daily Diary\n")
file.write("==============\n\n")
file.write("Today I learned Python file handling!\n")
file.write("It's amazing how I can save data permanently.\n")
print("Created and wrote to 'diary.txt'")
# Read the entire file
with open("diary.txt", "r") as file:
content = file.read()
print("\nFile contents:")
print(content)
print()
# ========== EXAMPLE 2: Appending to a File and Reading Line by Line ==========
print("=== Example 2: Append and Read Line by Line ===")
# Append to the file (adds to the end)
with open("diary.txt", "a") as file:
file.write("\nTomorrow I'll learn about error handling!\n")
file.write("I'm excited to continue learning Python.\n")
print("Appended new entries to 'diary.txt'")
# Read line by line using readlines()
print("\nReading line by line:")
with open("diary.txt", "r") as file:
lines = file.readlines()
for i, line in enumerate(lines, 1):
print(f"Line {i}: {line.strip()}")
print()
# ========== EXAMPLE 3: Working with CSV Files ==========
print("=== Example 3: Create and Read a CSV File ===")
# Create a CSV file (comma‑separated values)
with open("students.csv", "w") as file:
file.write("Name,Age,Grade\n")
file.write("Alice,20,A\n")
file.write("Bob,21,B\n")
file.write("Charlie,19,A\n")
print("Created 'students.csv'")
# Read and parse CSV manually
print("\nStudent Records:")
with open("students.csv", "r") as file:
for line in file:
name, age, grade = line.strip().split(",")
if name != "Name": # skip header
print(f"Student: {name}, Age: {age}, Grade: {grade}")
# Bonus: Check if file exists and get info
import os
print("\n--- File Info ---")
if os.path.exists("diary.txt"):
size = os.path.getsize("diary.txt")
print(f"'diary.txt' exists. Size: {size} bytes")
else:
print("File not found.")
→ Run this code interactively