1 of 23

BinaryTree

Intermediate

Python Course

BinaryTree Digital Education Program

2 of 23

Week 2

File Handling &

Basic Data Processing

3 of 23

Practice Question

Review: Which of the following could be initialized with the keyword 'int'?

A

100

B

5E10

C

6.00

D

3.14

E

5239400

5A

Think about what defines a valid integer in Python.

4 of 23

Looking Ahead

First: What is Machine Learning (ML)?

We're not tackling ML this week — but it's important to start thinking about how file handling and data processing skills connect to it.

→ What is supervised vs. unsupervised learning?

→ What are benefits and challenges of each technique?

5 of 23

Introduction to File Handling in Python

File handling lets you store, retrieve, read, and write data — essential for building real programs.

"r"

Read (default)

Opens for reading.

Raises an error if the file does not exist.

"w"

Write

Creates a new file, or overwrites

an existing one.

"a"

Append

Opens for writing without erasing content.

New data is added at the end.

open(file, mode) — used to handle files in Python

6 of 23

Handling CSV Files in Python

CSV = Comma-Separated Values. Each line is a row; values are separated by commas.

csv.writer()

Writes data into a CSV file

csv.reader()

Reads a CSV file line by line

DictWriter

Like csv.writer() but works with dictionaries

DictReader

Like csv.reader() but returns rows as dictionaries

7 of 23

Discussion Question

Regular Writing vs. Dictionary Writing

Can you tell what the benefit is to writing as a dictionary?

Hint: Think about what happens when the CSV file changes.

⏱ 5 Minutes

8 of 23

CSV vs. JSON — Comparison

Feature

CSV

JSON

Structure

Flat, tabular (rows & columns)

Nested / hierarchical

Parse speed

Fast

Slower

Data types

Everything stored as a string

Preserves native types (int, bool, etc.)

Best for

Spreadsheet-like data

Complex / nested structured data

9 of 23

Handling JSON Files in Python

JSON (JavaScript Object Notation) — a lightweight format for storing structured data.

json.dump()

Writes Python objects to a JSON file.

json.load()

Reads JSON data and converts it to a Python object.

import json��# Write�with open("data.json", "w") as f:� json.dump(my_data, f)��# Read�with open("data.json") as f:� data = json.load(f)

10 of 23

The "import" Keyword

Import a module

import csv

Load an entire standard library module.

Import a library

import pandas as pd

Load a third-party library (with alias).

Import a specific function

from json import load, dump

Load only what you need — avoids loading the whole module.

11 of 23

New Library

Introduction

to Pandas

Pandas is a Python library used for analyzing, cleaning, and manipulating data. Widely used in data science, machine learning, and AI.

import pandas as pd

12 of 23

Pandas — Series

A Series is a one-dimensional labeled array that holds data of any type. Think of it as a single column in a spreadsheet. Default index starts at 0.

import pandas as pd��# From a list�s1 = pd.Series([10, 20, 30, 40])��# From a dict�s2 = pd.Series({"a": 1, "b": 2, "c": 3})��# With a custom index�s3 = pd.Series([100, 200], index=["x", "y"])

13 of 23

Pandas — DataFrames

A DataFrame is a 2D table with rows and columns — like a spreadsheet in Python.

data = {� "Name": ["Alice", "Bob", "Charlie"],� "Age": [25, 30, 35],� "City": ["NY", "LA", "Chicago"]�}��df = pd.DataFrame(data)�print(df)��# Retrieve row with .loc�df.loc[0] # Returns first row as a Series

14 of 23

Reading CSV Files with Pandas

df = pd.read_csv("file.csv")�print(df.to_string()) # Print the entire DataFrame��# Pandas only shows first/last 5 rows by default�print(df) # Truncated view for large datasets

Tip: Use .to_string() to print the full DataFrame. For large datasets, Pandas truncates the output by default.

df.loc[0:1] → first two rows | df.loc[df["Age"] > 25] → conditional filter

15 of 23

Practice Question

What is the correct way to import the pandas library in Python?

A

import pandas as pd

B

import pd as pandas

C

import pandas.pd

D

import panda as pd

16 of 23

Practice Question

Which of the following is NOT true about a Pandas Series?

A

It is a one-dimensional labeled array.

B

It can hold different data types in a single column.

C

It is similar to a column in a DataFrame.

D

It requires multiple columns to be created.

17 of 23

Practice Question

Which of the following correctly reads a CSV file into a Pandas DataFrame?

A

df = pandas.read_csv("data.csv")

B

df = pd.read_csv("data.csv")

C

df = read_csv("data.csv")

D

df = pd.DataFrame("data.csv")

18 of 23

Practice Question

Which of the following correctly retrieves Bob's age using .loc? (Bob is at index 1)

A

df.loc[1, "Age"]

B

df.loc["Age", 1]

C

df.loc[1]["Age"]

D

df.loc(1, "Age")

19 of 23

Practice Question

How do you select the first two rows using .loc?

A

df.loc[0:2]

B

df.loc[0:1]

C

df.loc[:2]

D

df.loc[["0", "1"]]

20 of 23

Practice Question

Which command selects all rows where Age > 25?

A

df.loc[df["Age"] > 25]

B

df.loc["Age" > 25]

C

df.loc[df.Age > 25]

D

Both A and C

21 of 23

Practice Question

(Challenge) If a CSV has missing values, which ensures they are replaced with 'N/A' when reading?

A

df = pd.read_csv("data.csv", fillna="N/A")

B

df = pd.read_csv("data.csv", na_values="N/A")

C

df = pd.read_csv("data.csv").fillna("N/A")

D

df = pd.read_csv("data.csv", na_replace="N/A")

We haven't covered this explicitly — apply your reasoning!

22 of 23

Conceptual Review

Quick discussion:

→ Main differences between a CSV and a JSON?

→ Give an example of something you can import with the 'import' keyword.

→ Name one application of Pandas in machine learning.

23 of 23

Next Steps

Getting Set Up

1

Download Visual Studio Code: code.visualstudio.com/download

2

Watch the setup tutorial (link posted in Google Classroom)

3

Write a few lines of code demonstrating today's topics and post in Classroom!