Skip to content

Commit c515f9a

Browse files
Add python-csv materials for Reading and Writing CSV Files in Python
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
1 parent d867710 commit c515f9a

11 files changed

Lines changed: 154 additions & 0 deletions

python-csv/README.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# Reading and Writing CSV Files in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [Reading and Writing CSV Files in Python](https://realpython.com/python-csv/).
4+
5+
Consider creating a [Python virtual environment](https://realpython.com/python-virtual-environments-a-primer/) before installing the dependencies:
6+
7+
```shell
8+
$ python3 -m venv .venv/ --prompt python-csv
9+
$ source .venv/bin/activate
10+
(python-csv) $ python -m pip install -r requirements.txt
11+
```
12+
13+
The scripts read their data files from the current working directory, so run them from inside this folder:
14+
15+
```shell
16+
(python-csv) $ python read_csv_with_reader.py
17+
```
18+
19+
Each script holds the code from one section of the tutorial:
20+
21+
| File | Tutorial section |
22+
| --- | --- |
23+
| `read_csv_with_reader.py` | Reading CSV Files With `csv` |
24+
| `read_csv_into_dictionary.py` | Reading CSV Files Into a Dictionary With `csv` |
25+
| `write_csv_with_writer.py` | Writing CSV Files With `csv` |
26+
| `write_csv_from_dictionary.py` | Writing CSV File From a Dictionary With `csv` |
27+
| `read_csv_with_pandas.py` | Reading CSV Files With `pandas` |
28+
| `write_csv_with_pandas.py` | Writing CSV Files With `pandas` |
29+
30+
The examples that the tutorial shows at the interactive prompt are included in
31+
`read_csv_with_pandas.py` as `print()` calls, in the same order as the article,
32+
so that you can run the whole section as a single script.
33+
34+
There are also three data files used throughout the tutorial:
35+
36+
| File | Description |
37+
| --- | --- |
38+
| `employee_birthday.csv` | Employee names, departments, and birthday months read by the `csv` examples. |
39+
| `employee_addresses.csv` | Addresses containing an embedded comma, used to illustrate the optional `reader` parameters. |
40+
| `hrdata.csv` | Employee hire dates, salaries, and sick days read by the `pandas` examples. |
41+
42+
Running the writing examples creates `employee_file.csv`, `employee_file2.csv`,
43+
and `hrdata_modified.csv` in this folder. Those files aren't checked in, since
44+
the tutorial generates them.

python-csv/employee_addresses.csv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
name,address,date joined
2+
john smith,1132 Anywhere Lane Hoboken NJ, 07030,Jan 4
3+
erica meyers,1234 Smith Lane Hoboken NJ, 07030,March 2

python-csv/employee_birthday.csv

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
name,department,birthday month
2+
John Smith,Accounting,November
3+
Erica Meyers,IT,March

python-csv/hrdata.csv

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Name,Hire Date,Salary,Sick Days remaining
2+
Graham Chapman,03/15/14,50000.00,10
3+
John Cleese,06/01/15,65000.00,8
4+
Eric Idle,05/12/14,45000.00,10
5+
Terry Jones,11/01/13,70000.00,3
6+
Terry Gilliam,08/12/14,48000.00,7
7+
Michael Palin,05/23/13,66000.00,8
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import csv
2+
3+
with open("employee_birthday.csv", mode="r") as csv_file:
4+
csv_reader = csv.DictReader(csv_file)
5+
line_count = 0
6+
for row in csv_reader:
7+
if line_count == 0:
8+
print(f"Column names are {', '.join(row)}")
9+
line_count += 1
10+
print(
11+
f"\t{row['name']} works in the {row['department']} "
12+
f"department, and was born in {row['birthday month']}."
13+
)
14+
line_count += 1
15+
print(f"Processed {line_count} lines.")

python-csv/read_csv_with_pandas.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import pandas
2+
3+
df = pandas.read_csv("hrdata.csv")
4+
print(df)
5+
6+
print(type(df["Hire Date"][0]))
7+
8+
df = pandas.read_csv("hrdata.csv", index_col="Name")
9+
print(df)
10+
11+
df = pandas.read_csv(
12+
"hrdata.csv",
13+
index_col="Name",
14+
parse_dates=["Hire Date"],
15+
date_format="%m/%d/%y",
16+
)
17+
print(df)
18+
19+
print(type(df["Hire Date"].iloc[0]))
20+
21+
df = pandas.read_csv(
22+
"hrdata.csv",
23+
index_col="Employee",
24+
parse_dates=["Hired"],
25+
date_format="%m/%d/%y",
26+
header=0,
27+
names=["Employee", "Hired", "Salary", "Sick Days"],
28+
)
29+
print(df)

python-csv/read_csv_with_reader.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import csv
2+
3+
with open("employee_birthday.csv") as csv_file:
4+
csv_reader = csv.reader(csv_file, delimiter=",")
5+
line_count = 0
6+
for row in csv_reader:
7+
if line_count == 0:
8+
print(f"Column names are {', '.join(row)}")
9+
line_count += 1
10+
else:
11+
print(
12+
f"\t{row[0]} works in the {row[1]} department, and was born in {row[2]}."
13+
)
14+
line_count += 1
15+
print(f"Processed {line_count} lines.")

python-csv/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pandas==3.0.5
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import csv
2+
3+
with open("employee_file2.csv", mode="w", newline="") as csv_file:
4+
fieldnames = ["emp_name", "dept", "birth_month"]
5+
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
6+
7+
writer.writeheader()
8+
writer.writerow(
9+
{
10+
"emp_name": "John Smith",
11+
"dept": "Accounting",
12+
"birth_month": "November",
13+
}
14+
)
15+
writer.writerow(
16+
{"emp_name": "Erica Meyers", "dept": "IT", "birth_month": "March"}
17+
)
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import pandas
2+
3+
df = pandas.read_csv(
4+
"hrdata.csv",
5+
index_col="Employee",
6+
parse_dates=["Hired"],
7+
date_format="%m/%d/%y",
8+
header=0,
9+
names=["Employee", "Hired", "Salary", "Sick Days"],
10+
)
11+
df.to_csv("hrdata_modified.csv")

0 commit comments

Comments
 (0)