-
Notifications
You must be signed in to change notification settings - Fork 19
/
Loading_Cancer_Risk_Data.py
72 lines (49 loc) · 1.71 KB
/
Loading_Cancer_Risk_Data.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
62
63
64
65
66
67
68
69
70
71
"""
Week 3 practice project template for Python Data Analysis
Reading and writing CSV files using lists
"""
import csv
#########################################################
# Part 1 - Week 3
def print_table(table):
"""
Echo a nested listto the console
"""
for row in table:
print(row)
def read_csv_file(file_name):
"""
Given a CSV file, read the data into a nested list
Input: String corresponding to comma-separated CSV file
Output: Lists of lists consisting of the fields in the CSV file
"""
with open(file_name, newline='') as csvfile:
csv_table = []
listreader = csv.reader(csvfile)
for row in listreader:
csv_table.append(row)
return csv_table
def write_csv_file(csv_table, file_name):
"""
Input: Nested list csv_table and a string file_name
Action: Write fields in csv_table into a comma-separated CSV file with the name file_name
"""
with open(file_name, 'w', newline='') as csvfile:
csv_writer = csv.writer(csvfile)
for row in csv_table:
csv_writer.writerow(row)
def test_part1_code():
"""
Run examples that test the functions for part 1
"""
# Simple test for reader
test_table = read_csv_file("test_case.csv") # create a small CSV for this test
print_table(test_table)
print()
# Test the writer
cancer_risk_table = read_csv_file("cancer_risk05_v4_county.csv")
write_csv_file(cancer_risk_table, "cancer_risk05_v4_county_copy.csv")
cancer_risk_copy = read_csv_file("cancer_risk05_v4_county_copy.csv")
# Test whether two tables are the same
print(cancer_risk_table == cancer_risk_copy)
test_part1_code()