YouTip LogoYouTip

Python File Handling

Reading Files

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

# Read line by line
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())

# Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()

Writing Files

# Write (overwrites existing content)
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Second line\n")

# Append
with open("output.txt", "a") as f:
    f.write("Appended line\n")

# Write multiple lines
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

File Modes

# "r"  - Read (default)
# "w"  - Write (creates or overwrites)
# "a"  - Append (creates or adds to end)
# "x"  - Create (fails if file exists)
# "rb" - Read binary
# "wb" - Write binary

Working with Paths

import os

# Current directory
print(os.getcwd())

# List files
print(os.listdir("."))

# Check if file exists
print(os.path.exists("data.txt"))

# Join paths properly
path = os.path.join("folder", "subfolder", "file.txt")

CSV Files

import csv

# Read CSV
with open("data.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

# Write CSV
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])

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

JSON Files

import json

# Read JSON
with open("data.json", "r") as f:
    data = json.load(f)

# Write JSON
data = {"name": "Alice", "age": 25}
with open("output.json", "w") as f:
    json.dump(data, f, indent=2)

Summary

  • Always use with statement for file operations (auto-closes the file)
  • Mode "r" reads, "w" overwrites, "a" appends
  • csv and json modules handle structured file formats
  • os.path provides cross-platform path utilities
← Docker Compose Run CommandPython Functions and Modules β†’