Week 1 -Foundational Python

Python Setup

Data Types and Variables

Control Flow

Functions and Modules

Type Hinting

CLI Habits

Errors and Debugging

Logging in Python

File Operations

[Cloud] Azure Setup

Gotchas & Pitfalls

Practice

Assignment

Back to Track

File Operations

Almost every real program needs to work with files: reading configuration, processing data, or saving results.

In Python, file operations are built in. You don’t need to install any extra libraries to get started. In this chapter, you’ll learn how to:


Opening and Closing Files

The built-in function to work with files is open().

file = open("example.txt","r")

This opens a file called example.txt in read mode ("r"). However, files are system resources, if you forget to close them, you can cause bugs or resource leaks.

The with Statement (Recommended)

Python provides a safer pattern using with. It automatically closes the file for you.

with open("example.txt","r")as file:
    content = file.read()

print(content)

Once the with block ends, the file is closed—no matter what. You should always prefer this pattern.


File Modes

When opening a file, you must specify how you want to use it.

Common modes:

Mode Meaning
"r" Read (file must exist)
"w" Write (overwrites file if it exists)
"a" Append (adds to end of file)
"x" Create (fails if file exists)

Example:

with open("output.txt","w")as file:
    file.write("Hello, world!\\n")

⚠️ Be careful with "w" — it deletes the file contents if the file already exists.


Reading Files

Reading the Entire File

with open("example.txt","r")as file:
    content = file.read()

print(content)

This loads the entire file into memory. Fine for small files, but not ideal for large ones.


Reading Line by Line

with open("example.txt","r")as file:
    for line in file:
        print(line.strip())

This is memory-efficient and very common in real programs.


Writing Files

Writing Text

with open("notes.txt","w") as file:
    file.write("First line\\n")
    file.write("Second line\\n")

Appending Text

with open("notes.txt","a") as file:
    file.write("Another line\\n")

Working with File Paths

Hard-coding file paths like "data/file.csv" can cause problems across operating systems. Python’s standard library includes pathlib, which makes paths safer and clearer.

from pathlib import Path

data_dir = Path("data")
file_path = data_dir / "example.txt"

with open(file_path,"r") as file:
    print(file.read())

This works on macOS, Linux, and Windows.


Reading CSV Files

CSV (Comma-Separated Values) files are common for data exchange. Python includes a built-in csv module.

Example CSV File (users.csv)

id,name,email
1,Alice,[email protected]
2,Bob,[email protected]

Reading a CSV File

import csv

with open("users.csv","r", newline="") as file:
    reader = csv.DictReader(file)

for row in reader:
    print(row)

Output:

{'id': '1', 'name': 'Alice', 'email': '[email protected]'}
{'id': '2', 'name': 'Bob', 'email': '[email protected]'}

Notice:


Writing JSON Files

JSON is a very common output format for APIs, configuration, and data exchange. Python includes the json module.

Writing JSON

import json

data = {
"id":1,
"name":"Alice",
"active":True
}

with open("user.json","w")as file:
    json.dump(data, file, indent=2)

This creates a nicely formatted file:

{
"id":1,
"name":"Alice",
"active":true
}

CSV → JSON Example (Putting It Together)

This example reads a CSV file and writes a JSON file.

import csv
import json
from pathlibimport Path

input_path = Path("users.csv")
output_path = Path("users.json")

users = []

with open(input_path,"r", newline="")as file:
    reader = csv.DictReader(file)
for rowin reader:
        users.append(row)

with open(output_path,"w")as file:
    json.dump(users, file, indent=2)

This is a common real-world pattern.


Common Errors and How to Read Them

File Not Found

FileNotFoundError: [Errno 2] No such file or directory

Usually means: