-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path04_csv_data_parser.py
More file actions
36 lines (29 loc) · 878 Bytes
/
Copy path04_csv_data_parser.py
File metadata and controls
36 lines (29 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
Day 10: CSV Data Parser
Concept: Reading and writing tabular data using the 'csv' module.
"""
import csv
csv_file = "data.csv"
# 1. Writing to a CSV file
data = [
["Name", "Role", "Level"],
["Krish", "Admin", "Expert"],
["John", "User", "Beginner"],
["Sarah", "Dev", "Intermediate"]
]
with open(csv_file, mode="w", newline="") as f:
writer = csv.writer(f)
writer.writerows(data)
print(f"CSV data written to {csv_file}")
# 2. Reading from a CSV file
print("\nReading CSV data:")
with open(csv_file, mode="r") as f:
reader = csv.reader(f)
for row in reader:
print(f"Row: {row}")
# 3. Using DictReader (Maps columns to a dictionary)
print("\nUsing DictReader:")
with open(csv_file, mode="r") as f:
dict_reader = csv.DictReader(f)
for row in dict_reader:
print(f"{row['Name']} is a {row['Role']} ({row['Level']})")