'Importing CSV and converting object type of columns
I'm in week 3 of a Python class. We're going over creating functions, but the homework involves us importing a CSV file and changing the object type of the columns. The hard part here is we have not gone over CSVs at all, and is not responding to any emails (I looked in the book... we are in chapter 5, and CSVs aren't until chapter 12... even then, the book isn't super helpful.)
The homework problem is
Implement a function named "read_dataset_csv_file" that takes one parameter named "file_path" of type "str" and returns a "list" object containing "tuple" objects for each line in the csv file. The file_path parameter should reference a CSV file containing the dataset text. The first column in CSV file is a number, the second column is a number, and the third column is date text. For each line, convert the first two columns values to numbers and the thrid column values to date objects with the function above.
Where I am at so far is:
import datetime
import csv
def read_dataset_csv_file(file_path)-> list :
from csv import reader
with open(file_path, 'r') as read_obj:
csv_reader = reader(read_obj)
list_of_tuples = list(map(tuple, csv_reader))
print(list_of_tuples)
return list_of_tuples
test_dataset = read_dataset_csv_file("test.txt")
The tests the program needs to pass are:
assert isinstance(test_dataset[0],tuple)
assert isinstance(test_dataset[1],tuple)
assert isinstance(test_dataset[2],tuple)
assert isinstance(test_dataset[3],tuple)
assert isinstance(test_dataset[0][0],(float,int))
assert isinstance(test_dataset[1][0],(float,int))
assert isinstance(test_dataset[2][0],(float,int))
assert isinstance(test_dataset[3][0],(float,int))
assert isinstance(test_dataset[0][1],(float,int))
assert isinstance(test_dataset[1][1],(float,int))
assert isinstance(test_dataset[2][1],(float,int))
assert isinstance(test_dataset[3][1],(float,int))
assert isinstance(test_dataset[0][2],datetime.date)
assert isinstance(test_dataset[1][2],datetime.date)
assert isinstance(test_dataset[2][2],datetime.date)
assert isinstance(test_dataset[3][2],datetime.date)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
