intermediateFile Handling

File Handling

Read, write, and manage files using Python.

01Reading Files

Use the open() function with a context manager (with statement) for safe file handling.

Python
1# Writing a file first
2with open("example.txt", "w") as f:
3 f.write("Hello, File!\nSecond line.\n")
4
5# Reading the entire file
6with open("example.txt", "r") as f:
7 content = f.read()
8 print(content)
9
10# Reading line by line
11with open("example.txt", "r") as f:
12 for line in f:
13 print(line.strip())
Output
Hello, File!
Second line.

Hello, File!
Second line.

02File Modes

Common modes: "r" (read), "w" (write/overwrite), "a" (append), "x" (create), "b" (binary). Add "+" for read/write.

Python
1# Append to file
2with open("log.txt", "a") as f:
3 f.write("New log entry\n")
4
5# Read/write mode
6with open("data.txt", "w+") as f:
7 f.write("Hello")
8 f.seek(0) # go back to start
9 print(f.read()) # Hello
Output
Hello

03Working with JSON

Use the json module to read and write JSON data.

Python
1import json
2
3data = {"name": "Alice", "scores": [95, 87, 92]}
4
5# Write JSON
6with open("data.json", "w") as f:
7 json.dump(data, f, indent=2)
8
9# Read JSON
10with open("data.json", "r") as f:
11 loaded = json.load(f)
12 print(loaded["name"], loaded["scores"])
Output
Alice [95, 87, 92]