-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathcsvdata_to_dictionary.py
More file actions
38 lines (28 loc) Β· 1.26 KB
/
csvdata_to_dictionary.py
File metadata and controls
38 lines (28 loc) Β· 1.26 KB
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
import os # OS module provides a portable way of using operating system-dependent functionality
import csv # which is used to store tabular data or spreadsheet file format, which uses comma as delimiter or separator, and such filesare known as CSV files.
#import contains inbuilt functions to use
# Create a file with data in it
def create_file(filename):
with open(filename, "w") as file:
file.write("name,color,type\n")
file.write("carnation,pink,annual\n")
file.write("daffodil,yellow,perennial\n")
file.write("iris,blue,perennial\n")
file.write("poinsettia,red,perennial\n")
file.write("sunflower,yellow,annual\n")
# Read the file contents and format the information about each row
def contents_of_file(filename):
return_string = ""
# Call the function to create the file
create_file(filename)
# Open the file
with open(filename) as file:
# Read the rows of the file into a dictionary
reader = csv.DictReader(file)
# Process each item of the dictionary
for row in reader:
return_string += "a {} {} is {}\n".format(
row["color"], row["name"], row["type"])
return return_string
# Call the function
print(contents_of_file("flowers.csv"))