File Handling

Python FundamentalsFile I/OFree Lesson

Advertisement

Introduction

Python provides built-in functions for reading from and writing to files.

Reading Files

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

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

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

Writing Files

# Write (overwrites)
with open("output.txt", "w") as f:
    f.write("Hello, World!")

# Append
with open("log.txt", "a") as f:
    f.write("\nNew entry")

# Write multiple lines
lines = ["line1", "line2", "line3"]
with open("output.txt", "w") as f:
    f.write("\n".join(lines))

Working with CSV

import csv

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

# Writing CSV
data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(data)

Practice Problems

  1. Copy contents of one file to another
  2. Count lines, words, and characters in a file
  3. Search for pattern in file
  4. Read and parse CSV data
  5. Implement a simple text file editor

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement