The Data
Read it. Work with it. Save it.
1. Text Files
Python can read and write plain text files.
Use with to open a file safely. It closes automatically when done.
π§βπ» Read a File
with open("students.txt", "r") as file:
content = file.read()
print(content)Read Line by Line
with open("students.txt", "r") as file:
for line in file:
print(line.strip()).strip() removes the \n at the end of each line.
Write a File
with open("students.txt", "w") as file:
file.write("Ahmed\n")
file.write("Faadumo\n")
file.write("Hodan\n")"w" overwrites everything in the file.
Append to a File
with open("students.txt", "a") as file:
file.write("Bile\n")"a" adds to the end without erasing what's already there.
π Summary
| Task | Code |
|---|---|
| Read a file | open("file.txt", "r") |
| Read all text | file.read() |
| Read lines | for line in file: |
| Strip newlines | line.strip() |
| Append to a file | open("file.txt", "a") |
| Overwrite a file | open("file.txt", "w") |
| Safe open | with open(...) as file: |
2. CSV
CSV stands for Comma-Separated Values.
Each line is a row. Commas separate the columns.
name,course,score
Ahmed,Python,88
Faadumo,React,92
Hodan,Python,75Python has a built-in csv module. No install needed.
π§βπ» Read a CSV
import csv
with open("students.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)Each row is a list: ["Ahmed", "Python", "88"]
Read as Dictionaries
import csv
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"], row["score"])DictReader uses the first row as keys. Each row becomes a dictionary.
Write a CSV
import csv
with open("roster.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["name", "score"])
writer.writerow(["Ahmed", 88])
writer.writerow(["Faadumo", 92])π‘ Always pass newline="" when writing CSV. Without it you get blank lines on Windows.
π Summary
| Task | Code |
|---|---|
| Import | import csv |
| Read rows | csv.reader(file) |
| Read as dicts | csv.DictReader(file) |
| Write rows | csv.writer(file) |
| Write one row | writer.writerow([values]) |
| Avoid blank lines | newline="" |
3. JSON
JSON stores data as keys and values. It looks like a Python dictionary.
{
"name": "Ahmed",
"course": "Python",
"score": 88
}A JSON file can also hold a list of items:
[
{"name": "Ahmed", "score": 88},
{"name": "Faadumo", "score": 92},
{"name": "Hodan", "score": 75}
]π§βπ» Read JSON
import json
with open("students.json", "r") as file:
data = json.load(file)
print(data)json.load() turns the file into a Python dictionary or list.
Write JSON
import json
students = [
{"name": "Ahmed", "score": 88},
{"name": "Faadumo", "score": 92}
]
with open("roster.json", "w") as file:
json.dump(students, file, indent=2)indent=2 makes the file readable. Without it everything is on one line.
π Summary
| Task | Code |
|---|---|
| Import | import json |
| Read JSON | json.load(file) |
| Write JSON | json.dump(data, file) |
| Pretty print | indent=2 |
| Result type | Dictionary or list |
4. Pandas
Pandas turns your data into a table you can work with in code.
That table is called a DataFrame.
π§βπ» Install
uv add pandasRead a CSV
import pandas as pd
df = pd.read_csv("students.csv")
print(df) name course score
0 Ahmed Python 88
1 Faadumo React 92
2 Hodan Python 75Read JSON
df = pd.read_json("students.json")
print(df)Same result. Different source file, same DataFrame.
Inspect the Data
df.head() # First 5 rows
df.info() # Column names, types, missing values
df.describe() # Count, mean, min, max for numbersSeries
A single column is called a Series.
names = df["name"]
print(names)0 Ahmed
1 Faadumo
2 Hodan
Name: name, dtype: objectπ‘ DataFrame = the whole table. Series = one column.
π Summary
| Task | Code |
|---|---|
| Install | uv add pandas |
| Import | import pandas as pd |
| Read CSV | pd.read_csv("file.csv") |
| Read JSON | pd.read_json("file.json") |
| First 5 rows | df.head() |
| Column info | df.info() |
| Stats | df.describe() |
| One column | df["column"] |
5. Filter, Sort, Save
Select Columns
df[["name", "score"]]Double brackets for multiple columns.
Filter Rows
df[df["course"] == "Python"]Returns only rows where course is "Python".
Multiple Conditions
df[(df["course"] == "Python") & (df["score"] > 80)]& means AND. Each condition needs its own parentheses.
Loc
loc selects by name. You tell it what you want using column names and conditions.
"Give me the name of everyone who scored above 80."
df.loc[df["score"] > 80, "name"]"Give me the name and course of everyone who scored above 80."
df.loc[df["score"] > 80, ["name", "course"]]π‘ loc stands for location. You locate data by name.
Sort
df.sort_values("score") # Low to high
df.sort_values("score", ascending=False) # High to lowSave to CSV
df.to_csv("filtered.csv", index=False)Save to JSON
df.to_json("filtered.json", orient="records", indent=2)index=False removes the row numbers from the output.
orient="records" saves as a list of objects (the clean format).
π Summary
| Task | Code |
|---|---|
| Select columns | df[["col1", "col2"]] |
| Filter rows | df[df["col"] == "value"] |
| AND condition | (cond1) & (cond2) |
| Select by label | df.loc[condition, "col"] |
| Sort ascending | df.sort_values("col") |
| Sort descending | ascending=False |
| Save CSV | df.to_csv("file.csv", index=False) |
| Save JSON | df.to_json("file.json", orient="records") |
6. File Uploader
Let the user upload a file directly in Streamlit.
π§βπ» Upload a CSV
import streamlit as st
import pandas as pd
uploaded = st.file_uploader("Upload a CSV", type="csv")
if uploaded:
df = pd.read_csv(uploaded)
st.dataframe(df)st.file_uploader returns the file. Pass it straight to Pandas.
st.dataframe displays the table with sorting and scrolling built in.
Upload JSON
uploaded = st.file_uploader("Upload JSON", type="json")
if uploaded:
df = pd.read_json(uploaded)
st.dataframe(df)Accept Multiple Types
uploaded = st.file_uploader("Upload a file", type=["csv", "json"])
if uploaded:
if uploaded.name.endswith(".csv"):
df = pd.read_csv(uploaded)
else:
df = pd.read_json(uploaded)
st.dataframe(df)π‘ Always check if uploaded: before reading. The file is None until the user picks one.
π Summary
| Task | Code |
|---|---|
| Upload widget | st.file_uploader("label", type="csv") |
| Multiple types | type=["csv", "json"] |
| Read uploaded CSV | pd.read_csv(uploaded) |
| Read uploaded JSON | pd.read_json(uploaded) |
| Display table | st.dataframe(df) |
| Check if uploaded | if uploaded: |