File I/O
## Learning Objectives
- Read from and write to files
- Work with different file modes
- Handle file paths
- Use context managers
## Opening Files
### Basic Syntax
```python
file = open("filename.txt", "r") # Open for reading
content = file.read()
file.close()
```
### File Modes
| Mode | Description |
|------|-------------|
| `r` | Read (default) |
| `w` | Write (overwrites) |
| `a` | Append |
| `x` | Create (fails if exists) |
| `b` | Binary mode |
| `+` | Read and write |
```python
# Text modes
file = open("file.txt", "r") # Read text
file = open("file.txt", "w") # Write text
file = open("file.txt", "a") # Append text
file = open("file.txt", "x") # Create text
# Binary modes
file = open("image.png", "rb") # Read binary
file = open("output.png", "wb") # Write binary
```
## Reading Files
### read()
```python
file = open("file.txt", "r")
content = file.read() # Read entire file
file.close()
# With encoding
file = open("file.txt", "r", encoding="utf-8")
```
### readline()
```python
file = open("file.txt", "r")
line1 = file.readline() # First line
line2 = file.readline() # Second line
file.close()
```
### readlines()
```python
file = open("file.txt", "r")
lines = file.readlines() # List of all lines
file.close()
# Or iterate directly
for line in open("file.txt", "r"):
print(line.strip())
```
## Writing Files
### write()
```python
file = open("output.txt", "w")
file.write("Hello, World!\n")
file.write("Second line")
file.close()
```
### writelines()
```python
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("output.txt", "w")
file.writelines(lines)
file.close()
```
## Context Managers (Recommended)
### Using with Statement
```python
# Automatically closes file
with open("file.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here
with open("output.txt", "w") as file:
file.write("Hello!\n")
file.write("World!")
# File is automatically closed here
```
### Multiple Files
```python
with open("input.txt", "r") as infile, open("output.txt", "w") as outfile:
for line in infile:
outfile.write(line.upper())
```
## File Paths
### Path Handling
```python
import os
# Current directory
print(os.getcwd())
# Join paths
path = os.path.join("folder", "subfolder", "file.txt")
print(path) # folder/subfolder/file.txt
# Get parts
print(os.path.basename("/path/to/file.txt")) # file.txt
print(os.path.dirname("/path/to/file.txt")) # /path/to
print(os.path.splitext("/path/to/file.txt")) # ('/path/to/file', '.txt')
```
### Pathlib (Modern)
```python
from pathlib import Path
# Create path
p = Path("folder", "file.txt")
# Check
print(p.exists())
print(p.is_file())
print(p.is_dir())
# Read/Write
content = p.read_text()
p.write_text("Hello!")
# List directory
for item in Path(".").iterdir():
print(item.name)
# Glob
for py_file in Path(".").glob("*.py"):
print(py_file)
```
## Reading CSV Files
### CSV Module
```python
import csv
# Reading
with open("data.csv", "r", newline="") as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
# Reading as dict
with open("data.csv", "r", newline="") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row["name"], row["age"])
```
### Writing CSV
```python
import csv
with open("output.csv", "w", newline="") as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Name", "Age"])
writer.writerow(["Alice", 25])
writer.writerow(["Bob", 30])
# Writing dicts
with open("output.csv", "w", newline="") as csvfile:
fieldnames = ["Name", "Age"]
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerow({"Name": "Alice", "Age": 25})
```
## Reading JSON
### json Module
```python
import json
# Reading
with open("data.json", "r") as jsonfile:
data = json.load(jsonfile)
print(data["name"])
# Writing
data = {"name": "Alice", "age": 25, "cities": ["NYC", "LA"]}
with open("output.json", "w") as jsonfile:
json.dump(data, jsonfile, indent=2)
# Pretty print
print(json.dumps(data, indent=2))
```
## Working with Binary Files
### Reading
```python
with open("image.png", "rb") as file:
data = file.read()
print(f"Read {len(data)} bytes")
```
### Copying a File
```python
with open("source.png", "rb") as source, open("dest.png", "wb") as dest:
dest.write(source.read())
```
## File Information
```python
import os
# Check existence
print(os.path.exists("file.txt"))
# File size
print(os.path.getsize("file.txt"), "bytes")
# Modification time
import datetime
mtime = os.path.getmtime("file.txt")
print(datetime.datetime.fromtimestamp(mtime))
```
## Common Patterns
### Read All Lines
```python
with open("file.txt", "r") as file:
lines = file.readlines()
# Or
with open("file.txt", "r") as file:
lines = file.read().splitlines()
```
### Filter Lines
```python
with open("file.txt", "r") as file:
filtered = [line.strip() for line in file if "pattern" in line]
```
### Append to File
```python
with open("log.txt", "a") as file:
file.write("New log entry\n")
```
## Summary
- Open files with `open(filename, mode)`
- Always use context manager (`with` statement)
- Modes: `r`, `w`, `a`, `x`, `b`, `+`
- Read: `read()`, `readline()`, `readlines()`
- Write: `write()`, `writelines()`
- Use `pathlib.Path` for modern path handling
- Use `csv` and `json` modules for structured files
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →