File I/O
Reading and writing files
Introduction
In this lesson, you'll learn about file i/o in Python. Coming from C, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In C, you're familiar with reading and writing files.
Python has its own approach to reading and writing files, which we'll explore step by step.
The Python Way
Let's see how Python handles this concept. Here's a typical example:
# Write to file — 'with' ensures file is closed
with open("output.txt", "w") as f:
f.write("Hello, World!\n")
# Read all at once
with open("input.txt", "r") as f:
content = f.read()
# Read line by line
with open("input.txt", "r") as f:
for line in f:
print(line.rstrip())
# Read all lines as list
with open("input.txt") as f:
lines = f.readlines()
# pathlib — modern approach
from pathlib import Path
text = Path("input.txt").read_text()
Path("output.txt").write_text("Hello!")Comparing to C
Here's how you might have written similar code in C:
#include <stdio.h>
#include <string.h>
/* Write to file */
FILE *f = fopen("output.txt", "w");
if (!f) { perror("fopen"); return 1; }
fprintf(f, "Hello, World!\n");
fclose(f);
/* Read line by line */
FILE *r = fopen("input.txt", "r");
if (!r) { perror("fopen"); return 1; }
char line[256];
while (fgets(line, sizeof(line), r)) {
/* strip newline */
line[strcspn(line, "\n")] = '\0';
printf("%s\n", line);
}
fclose(r);You may be used to different syntax or behavior.
C: fopen/fclose — Python: with open() (auto-closes)
You may be used to different syntax or behavior.
C fgets needs buffer size; Python reads strings of any size
You may be used to different syntax or behavior.
Python 'with' statement replaces C's explicit fclose pattern
You may be used to different syntax or behavior.
pathlib provides an object-oriented file API
Step-by-Step Breakdown
1. Context Managers (with)
Python's 'with' statement automatically closes the file even if an exception occurs — replacing C's explicit fclose.
FILE *f = fopen("file.txt", "r");
// ... use f ...
fclose(f);with open("file.txt", "r") as f:
content = f.read()
# automatically closed here2. Reading Modes
Python's open() modes mirror C's fopen modes: 'r' read, 'w' write, 'a' append, 'rb'/'wb' for binary.
3. pathlib
For simple file operations, pathlib.Path provides one-liners that replace multiple lines of C file handling.
from pathlib import Path
data = Path("config.json").read_text()
Path("output.txt").write_text("result")Common Mistakes
When coming from C, developers often make these mistakes:
- C: fopen/fclose — Python: with open() (auto-closes)
- C fgets needs buffer size; Python reads strings of any size
- Python 'with' statement replaces C's explicit fclose pattern
Key Takeaways
- fopen/fclose → with open() (auto-close)
- fgets with buffer → f.readline() or iterate file object
- pathlib for simple read/write one-liners
- No buffer overflow concerns in Python