File I/O
Reading and writing files
Introduction
In this lesson, you'll learn about file i/o in Python. Coming from Java, you already have a foundation for understanding this concept. We'll build on that knowledge while highlighting the key differences.
In Java, 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 all text
content = Path("input.txt").read_text()
# Write
Path("output.txt").write_text("Hello!")
# Line by line — with auto-close
with open("input.txt") as f:
for line in f:
print(line.rstrip())
# List directory
for p in Path(".").iterdir():
print(p)
# Check exists / glob
if Path("config.txt").exists():
configs = list(Path(".").glob("*.json"))Comparing to Java
Here's how you might have written similar code in Java:
import java.nio.file.*;
import java.io.*;
// Read all text (Java 11+)
String content = Files.readString(Path.of("input.txt"));
// Write
Files.writeString(Path.of("output.txt"), "Hello!");
// Line by line
try (BufferedReader br = new BufferedReader(
new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
// List directory
Files.list(Path.of("."))
.forEach(System.out::println);You may be used to different syntax or behavior.
Python pathlib.Path = Java's java.nio.file.Path
You may be used to different syntax or behavior.
Python 'with open()' = Java try-with-resources
You may be used to different syntax or behavior.
Python Path.read_text() = Java Files.readString()
You may be used to different syntax or behavior.
Python iteration over file object = Java BufferedReader loop
Step-by-Step Breakdown
1. One-liner Read/Write
Python's pathlib provides clean one-liners for common operations, similar to Java's Files.readString/writeString (Java 11+).
Files.readString(Path.of("file.txt"))Path("file.txt").read_text()2. with vs try-with-resources
Python's 'with' statement auto-closes files like Java's try-with-resources, but with cleaner syntax.
try (BufferedReader br = new BufferedReader(new FileReader("f.txt"))) { ... }with open("f.txt") as f: ...3. pathlib vs java.nio
Python's pathlib.Path object provides file operations as methods — similar to Java's Path + Files API.
Files.exists(path); Files.list(path)path.exists(); list(path.iterdir())Common Mistakes
When coming from Java, developers often make these mistakes:
- Python pathlib.Path = Java's java.nio.file.Path
- Python 'with open()' = Java try-with-resources
- Python Path.read_text() = Java Files.readString()
Key Takeaways
- pathlib.Path = java.nio.file.Path + Files
- with open() = try-with-resources
- read_text()/write_text() = readString()/writeString()
- Iterate file object directly for line-by-line