File I/O
Reading and writing files
Introduction
In this lesson, you'll learn about file i/o in Python. Coming from JavaScript, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In JavaScript, 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:
from pathlib import Path
# Read (context manager ensures file is closed)
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read() # entire file
# lines = f.readlines() # list of lines
# for line in f: ... # iterate lines
# Write
with open("out.txt", "w", encoding="utf-8") as f:
f.write("Hello!")
# Append
with open("log.txt", "a") as f:
f.write("New log entry\n")
# Path manipulation (pathlib)
base = Path(__file__).parent
full = base / "data" / "file.txt"
text = full.read_text(encoding="utf-8") # shortcutComparing to JavaScript
Here's how you might have written similar code in JavaScript:
import { readFileSync, writeFileSync, readFile } from "fs";
import { readFile as readFileAsync } from "fs/promises";
import path from "path";
// Sync read
const content = readFileSync("data.txt", "utf-8");
// Async read (callback)
readFile("data.txt", "utf-8", (err, data) => {
if (err) throw err;
console.log(data);
});
// Async read (promise)
const data = await readFileAsync("data.txt", "utf-8");
// Write
writeFileSync("out.txt", "Hello!", "utf-8");
// Path manipulation
const full = path.join(__dirname, "data", "file.txt");You may be used to different syntax or behavior.
with open() auto-closes the file — always use it
You may be used to different syntax or behavior.
pathlib.Path is more readable than path.join()
You may be used to different syntax or behavior.
Mode 'r'=read, 'w'=write (overwrite), 'a'=append
You may be used to different syntax or behavior.
No callback-based API — sync by default; use aiofiles for async
Step-by-Step Breakdown
1. Context Manager (with)
The with statement automatically closes the file when the block exits, even if an error occurs.
const f = fs.readFileSync("file.txt", "utf-8");with open("file.txt", "r") as f:
data = f.read()2. pathlib vs path.join
pathlib.Path uses / operator for joining paths and has many convenience methods.
path.join(__dirname, "data", "file.txt")Path(__file__).parent / "data" / "file.txt"3. File Modes
Python open() mode strings: 'r' read, 'w' write (truncate), 'a' append, 'b' binary, 'x' exclusive create.
// readFileSync / writeFileSync / appendFileSyncopen("f","r") # read
open("f","w") # write/overwrite
open("f","a") # append
open("f","rb") # binary readCommon Mistakes
When coming from JavaScript, developers often make these mistakes:
- with open() auto-closes the file — always use it
- pathlib.Path is more readable than path.join()
- Mode 'r'=read, 'w'=write (overwrite), 'a'=append
Key Takeaways
- with open() auto-closes — always use it
- pathlib.Path for clean path operations
- 'r','w','a','b' modes