Complete beginner-friendly notes explaining how Python reads, writes, and manages files in real-world projects.
File handling in Python means working with files stored on disk — reading data from them, writing data into them, and managing files and folders programmatically.
file = open("data.txt", "r")
| Mode | Description |
|---|---|
| r | Read file |
| w | Write (overwrite) |
| a | Append |
| x | Create new file |
| rb | Read binary |
| wb | Write binary |
The with statement automatically closes the file.
with open("data.txt", "r") as f:
data = f.read()
f.read()
f.readline()
f.readlines()
for line in f:
print(line.strip())
with open("out.txt", "w") as f:
f.write("Hello Python\n")
with open("log.txt", "a") as f:
f.write("New log entry\n")
f.tell()
```
f.seek(0)
import os
```
os.remove("file.txt")
os.rename("a.txt", "b.txt")
os.mkdir("folder")
os.listdir(".")
import csv
```
with open("data.csv") as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
import json
```
with open("data.json", "w") as f:
json.dump({"name": "Amit"}, f)