-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrite_read_csv.py
61 lines (42 loc) · 1.45 KB
/
write_read_csv.py
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Practice Programs for lambda functions
"""
import csv
from typing import Any, List, Tuple, Union
type_user_data = Union[List[Tuple[str, str, int]], Any]
def write_csv(file_path: str, user_data: type_user_data) -> None:
"""
Write User info to csv file
It takes two parameters
file_path : type string, refers to the csv file path
user_data : type dictionary, refer to the user details
"""
COLUMNS: List[str] = ["Name", "Email", "Age"]
with open(file_path, "w", encoding="utf-8", newline="") as file:
writer = csv.writer(file)
writer.writerow(COLUMNS)
writer.writerows(user_data)
def read_csv(file_path: str) -> type_user_data:
"""
Reads the CSV file
It takes one argument
file_path: type string, refers to the csv file path
returns a list of tuples
"""
user_data: type_user_data = []
with open(file_path, "r", encoding="utf-8") as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
user_data.append((row[0], row[1], int(row[2])))
return user_data
FILE_PATH: str = "./new_users.csv"
USER_DATA: type_user_data = [
("Sarmad", "sarmad@email.com", 19),
("Nawaz", "nawaz@email.com", 23),
("Mubashir", "mubashir@email.com", 17),
]
write_csv(FILE_PATH, USER_DATA)
data = read_csv(FILE_PATH)
for name, email, age in data:
print(f"{name} with email ({email}) is {age} years old.")