intermediateFile Handling
File Handling
Read, write, and manage files using Python.
In this lesson
01Reading Files
Use the open() function with a context manager (with statement) for safe file handling.
Python
1# Writing a file first2with open("example.txt", "w") as f:3 f.write("Hello, File!\nSecond line.\n")45# Reading the entire file6with open("example.txt", "r") as f:7 content = f.read()8 print(content)910# Reading line by line11with 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 file2with open("log.txt", "a") as f:3 f.write("New log entry\n")45# Read/write mode6with open("data.txt", "w+") as f:7 f.write("Hello")8 f.seek(0) # go back to start9 print(f.read()) # Hello
Output
Hello
03Working with JSON
Use the json module to read and write JSON data.
Python
1import json23data = {"name": "Alice", "scores": [95, 87, 92]}45# Write JSON6with open("data.json", "w") as f:7 json.dump(data, f, indent=2)89# Read JSON10with open("data.json", "r") as f:11 loaded = json.load(f)12 print(loaded["name"], loaded["scores"])
Output
Alice [95, 87, 92]