#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
6 min read
•Question 11 of 41easy

File Handling in Python

Reading and writing files.

What You'll Learn

  • How to read and write files in Python
  • The importance of context managers (with statement)
  • Different file modes and when to use them
  • Working with JSON and CSV files
  • Best practices for file handling

Understanding File Handling

File handling is essential for persisting data, processing logs, configuration management, and data exchange. Python makes file operations simple with built-in functions and context managers.

The Context Manager (with Statement)

Always use with statement - it automatically closes files even if exceptions occur:

code.pyPython
# GOOD - File automatically closed
with open("file.txt", "r") as f:
    content = f.read()
# File closed automatically here

# BAD - Must remember to close
f = open("file.txt", "r")
content = f.read()
f.close()  # Easy to forget!

Reading Files

code.pyPython
# Read entire file as string
with open("file.txt", "r") as f:
    content = f.read()
    print(content)

# Read all lines as list
with open("file.txt", "r") as f:
    lines = f.readlines()  # ['line1\n', 'line2\n', ...]

# Read line by line (memory efficient for large files)
with open("file.txt", "r") as f:
    for line in f:
        print(line.strip())  # Remove trailing newline

# Read specific number of characters
with open("file.txt", "r") as f:
    chunk = f.read(100)  # First 100 characters

# Read single line
with open("file.txt", "r") as f:
    first_line = f.readline()
    second_line = f.readline()

Writing Files

code.pyPython
# Write (creates or overwrites)
with open("file.txt", "w") as f:
    f.write("Hello, World!")

# Write multiple lines
with open("file.txt", "w") as f:
    lines = ["Line 1", "Line 2", "Line 3"]
    for line in lines:
        f.write(line + "\n")

# writelines (doesn't add newlines)
with open("file.txt", "w") as f:
    lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
    f.writelines(lines)

# Append (adds to end of file)
with open("file.txt", "a") as f:
    f.write("\nNew line at end")

File Modes

ModeDescription
rRead (default), error if not exists
wWrite, creates or overwrites
aAppend, creates if not exists
xCreate, error if exists
r+Read and write
w+Write and read (overwrites)
a+Append and read
bBinary mode (add to others: rb, wb)
code.pyPython
# Binary mode (images, PDFs, etc.)
with open("image.png", "rb") as f:
    data = f.read()

with open("copy.png", "wb") as f:
    f.write(data)

Working with JSON

code.pyPython
import json

# Python dict to JSON file
data = {"name": "John", "age": 30, "cities": ["NYC", "LA"]}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)  # Pretty print

# JSON file to Python dict
with open("data.json", "r") as f:
    data = json.load(f)
    print(data["name"])

# String conversion
json_string = json.dumps(data)  # Dict to string
data = json.loads(json_string)  # String to dict

Working with CSV

code.pyPython
import csv

# Write CSV
with open("data.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age", "City"])
    writer.writerow(["Alice", 25, "NYC"])
    writer.writerow(["Bob", 30, "LA"])

# Read CSV
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)  # ['Name', 'Age', 'City']

# DictReader/DictWriter
with open("data.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row["Name"], row["Age"])

Path Operations

code.pyPython
from pathlib import Path

# Modern path handling (Python 3.4+)
path = Path("folder/file.txt")

# Check existence
path.exists()
path.is_file()
path.is_dir()

# Create directories
Path("new/folder").mkdir(parents=True, exist_ok=True)

# Read/write shortcuts
content = path.read_text()
path.write_text("Hello!")

# Iterate files
for file in Path(".").glob("*.txt"):
    print(file)

Interview Tip

When asked about Python file handling:

  1. Always use with statement (context manager)
  2. Know the difference between read modes (r, rb, r+)
  3. json.dump/load for files, dumps/loads for strings
  4. Use pathlib.Path for modern path operations
  5. Binary mode (b) for non-text files