Read data from a CSV file
Create a function called read_user_data that reads the first data record from user_data.csv and returns a message in the format shown in Listing 1.
Use csv.DictReader so the values are accessed through the column names rather than numerical positions. Print the returned message to display it in the console.
The supplied create_sample_file helper creates a complete disposable input file, so no other exercise must be completed first.
TipString interpolation and new lines
Use an f-string to insert values into text, for example, f"Name: {user['Name']}". Use \n to add a new line inside a string.
Use the supplied helper and function template in Listing 2.
import csv
from pathlib import Path
def create_sample_file(file_path: Path) -> None:
with file_path.open("w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Email Address"])
writer.writerow(["Alex", 19, "alex@example.com"])
def read_user_data(file_path: Path) -> str:
# Read and format the first data record beneath the CSV header.
raise NotImplementedErrorCreate a disposable file with create_sample_file, call read_user_data, and verify that the returned message contains all three values.