File I/O

Python makes it incredibly easy to work with files. The built-in open()function is the starting point for most file operations.

1. Reading Files

Always use the with statement. It automatically closes the file for you.

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

2. Writing Files

  • 'w': Write (Overwrites existing content).
  • 'a': Append (Adds to the end).
with open("output.txt", "w") as f:
    f.write("Hello from Python!\n")
    f.write("Line 2")

3. Working with JSON

JSON is common for APIs and configuration settings.

import json

data = {"name": "Pradeep", "active": True}

# Convert Python dict to JSON file
with open("user.json", "w") as f:
    json.dump(data, f)

# Read JSON back to dict
with open("user.json", "r") as f:
    user = json.load(f)
Security: Be careful when reading files from untrusted sources to avoid directory traversal attacks.