techmore.in

Python - File Handling

What is File Handling?

File handling in Python allows you to read from and write to files, making it essential for data persistence and input/output operations in real-world applications.

Opening and Reading Files

You can open a file using the open() function and read its contents using methods like read(), readline(), or readlines().

python
# Reading a file
file = open("sample.txt", "r")
print(file.read())
file.close()

Using with Statement (Context Manager)

The with statement ensures proper resource management and automatically closes the file.

python
# Safely reading a file
with open("sample.txt", "r") as file:
    print(file.read())

Writing to Files

You can write to a file using write() or writelines() methods. Use "w" for write mode or "a" for append mode.

python
# Writing to a file
with open("output.txt", "w") as file:
    file.write("Hello, world!")

File Modes

  • r: Read (default)
  • w: Write (overwrite)
  • a: Append
  • r+: Read and Write
  • rb, wb: Binary modes

Working with CSV Files

Python’s csv module helps read and write CSV (Comma-Separated Values) files.

python
import csv

# Writing to a CSV
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])

Working with JSON Files

Use the json module to serialize Python objects into JSON format or parse JSON back to Python objects.

python
import json

data = {"name": "Alice", "age": 25}

# Writing JSON
with open("data.json", "w") as file:
    json.dump(data, file)

# Reading JSON
with open("data.json", "r") as file:
    loaded = json.load(file)
    print(loaded)

Pros and Cons of File Handling

  • Pros: Enables persistent storage, easy data exchange with CSV/JSON.
  • Cons: Risk of data loss if not handled properly (e.g., overwriting, unclosed files).