Python 24-Day Course - Day 11: File I/O

Day 11: File I/O

Writing to a File

with open("hello.txt", "w", encoding="utf-8") as f:
    f.write("Hello\n")
    f.write("Python file I/O\n")

Reading a File

# Read entire file
with open("hello.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# Read line by line
with open("hello.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

File Modes

ModeDescription
rRead (default)
wWrite (overwrite)
aAppend
xCreate new file (error if already exists)
rb / wbBinary read/write

CSV File Processing

import csv

# Write CSV
data = [["Name", "Age", "City"], ["Alice", 25, "Seoul"], ["Bob", 30, "Busan"]]
with open("data.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(data)

# Read CSV
with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(f"{row['Name']} - age {row['Age']}")

Checking File Existence

from pathlib import Path

file_path = Path("hello.txt")
if file_path.exists():
    print(f"File size: {file_path.stat().st_size} bytes")
else:
    print("File does not exist")

Today’s Exercises

  1. Create a notepad that takes user input and appends each line to a text file.
  2. Write a program that calculates the average of a specific column from a CSV file.
  3. Write a program that counts the words, lines, and characters in a text file.

Was this article helpful?