📁

How to Handle Files in Python

PythonIntermediate

Read and write files using Python's file handling.

Code Example

Python
# File-like operations with StringIO
from io import StringIO

# Write to a "file" in memory
buffer = StringIO()
buffer.write("Line 1: Hello\n")
buffer.write("Line 2: World\n")
buffer.write("Line 3: Python\n")

# Read from the buffer
content = buffer.getvalue()
print("File content:")
print(content)

# Working with CSV-like data
import csv
import io

csv_data = "name,age,city\nAlice,30,NYC\nBob,25,LA\nCharlie,35,Chicago"
reader = csv.DictReader(io.StringIO(csv_data))

print("\nCSV Data:")
for row in reader:
    print(f"  {row['name']}, {row['age']}, {row['city']}")

Explanation

Use StringIO for in-memory file operations. The csv module handles CSV data. Use "with open()" for real files.

Related Tutorials