Course: before Q5 in-class exercises
Processing CSV and JSON:
Problem 1: Create a csv file and saves the a few records in the format: number;studentname;course;grade
When writing the file include a header row
def ex1():
with open("students.csv", "w") as csvfile:
writer = csv.DictReader(csvfile, delimiter=';', lineterminator='\n')
data = ["number", "studentname", "course", "grade"]
writer.writerow(data)
writer.writerows ([
["123", "John Smith", "C++", "100.0"],
["123", "John Smith", "C++", "100.0"],
["123", "John Smith", "C++", "100.0"]
])
ex1()Task 7: Read the file, created from exercise 1 by creating a list that contains information about which students enrolled in a certain course:
{
‘course1’: [‘student1’, ’student2’],
‘course2’: [‘student3’]
}
Note: You could extend the previous exercise, by making the grouping after the list of dictionaries was created.
def ex1():
with open("students.csv", "w") as csvfile:
writer = csv.DictReader(csvfile, delimiter=';', lineterminator='\n')
data = ["number", "studentname", "course", "grade"]
writer.writerow(data)
writer.writerows ([
["123", "John Smith", "C++", "100.0"],
["124", "John Smith1", "C++", "100.0"],
["125", "John Smith2", "Python", "100.0"],
["126", "John Smith3", "Python", "100.0"],
["127", "John Smith4", "FDS", "100.0"]
])
def ex7():
try:
with open("students.csv", "r") as csvfile:
stats = {}
reader = csv.DictReader(csvfile, delimiter=';', lineterminator='\n')
for row in reader:
if row["studentname"] not in stats:
stats[row["studentname"]] = []
stats["course"].append(row["course"])
except FileNotFoundError:
print("File not found")Task 8: Read the file, created from exercise 1 by creating a list that contains information about which students enrolled in a certain course and the average score of all the students that enrolled in that course:
{
‘course1’: {
‘members’: [‘student1’, ’student2’],
‘scores’: [100, 81],
‘avgScore’: 90.5
}
‘course2’: {
‘members’: [‘student3’],
‘scores’: [100]
‘avgScore’: 100
}
Note: You could extend any of the previous exercises to complete this one.
def ex1():
with open("students.csv", "w") as csvfile:
writer = csv.DictReader(csvfile, delimiter=';', lineterminator='\n')
data = ["number", "studentname", "course", "grade"]
writer.writerow(data)
writer.writerows ([
["123", "John Smith", "C++", "100.0"],
["124", "John Smith1", "C++", "100.0"],
["125", "John Smith2", "Python", "100.0"],
["126", "John Smith3", "Python", "100.0"],
["127", "John Smith4", "FDS", "100.0"]
])
def ex8():
try:
with open("students.csv", "r") as csvfile:
stats = {}
reader = csv.DictReader(csvfile, delimiter=';', lineterminator='\n')
for row in reader:
try:
if row["studentname"] not in stats:
stats[row["course"]] = dict(members=[], scores=[], avgScores=[])
stats[row["course"]]["members"].append(row["studentname"])
stats[row["course"]]["scores"].append(row["studentname"])
except ValueError as e:
print(e)
except FileNotFoundError:
print("File not found")