Python File Handling

Complete beginner-friendly notes explaining how Python reads, writes, and manages files in real-world projects.

1. What is File Handling?

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.

2. Opening a File

file = open("data.txt", "r")

File Modes

Mode Description
r Read file
w Write (overwrite)
a Append
x Create new file
rb Read binary
wb Write binary

3. Best Practice: with Statement

The with statement automatically closes the file.

with open("data.txt", "r") as f:
data = f.read()

4. Reading Files

read()

f.read()

readline()

f.readline()

readlines()

f.readlines()

Looping through file

for line in f:
print(line.strip())

5. Writing & Appending Files

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")

6. File Cursor Control

f.tell()
```

f.seek(0)
```

7. File & Directory Management

import os
```

os.remove("file.txt")
os.rename("a.txt", "b.txt")
os.mkdir("folder")
os.listdir(".")
```

8. CSV & JSON Files

CSV

import csv
```

with open("data.csv") as f:
reader = csv.reader(f)
for row in reader:
print(row)
```

JSON

import json
```

with open("data.json", "w") as f:
json.dump({"name": "Amit"}, f)
```

Real-World Uses