BinaryTree
Intermediate
Python Course
BinaryTree Digital Education Program
Week 2
File Handling &
Basic Data Processing
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.
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?
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
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
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
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 |
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)
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.
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
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"])
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
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
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
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.
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")
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")
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"]]
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
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!
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.
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!