This solution follows the exercise on dictionary data from CSV-style rows. It keeps the original exercise approach of working without the csv module, while using context managers so files are closed automatically.
student.csv with student name, Physics, Chemistry, Math and attendance data.2.student1.csv from the dictionary.student2.csv after reducing the Physics mark by 2.1,Ravi,20,30,40,120
2,Raju,30,40,50,130
3,Alex,40,50,60,140
4,Ronn,50,60,70,150
with open('student.csv', 'w', encoding='utf-8') as file:
for student_id in range(1, 5):
name = input('Student name: ')
physics = input('Physics marks: ')
chemistry = input('Chemistry marks: ')
math = input('Math marks: ')
attendance = input('Days present: ')
row = f'{student_id},{name},{physics},{chemistry},{math},{attendance}\n'
file.write(row)
Opening the file in w mode makes repeated practice runs predictable instead of appending duplicate records.
students = {}
with open('student.csv', 'r', encoding='utf-8') as file:
for record in file:
parts = record.rstrip('\n').split(',')
student_id = parts[0]
students[student_id] = parts[1:]
print(students)
print(students['2'])
The value stored for each ID is a list in this order: name, Physics, Chemistry, Math and attendance. The rstrip() call removes the line break before splitting the row.
with open('student1.csv', 'w', encoding='utf-8') as file:
for student_id, details in students.items():
row = ','.join([student_id, *details]) + '\n'
file.write(row)
with open('student2.csv', 'w', encoding='utf-8') as file:
for student_id, details in students.items():
name, physics, chemistry, math, attendance = details
physics = str(int(physics) - 2)
row = ','.join([student_id, name, physics, chemistry, math, attendance]) + '\n'
file.write(row)
This corrects the intended exercise operation by changing the Physics field specifically. int() converts the mark for arithmetic and str() converts it back for file output.
Download the original exercise ZIP / notebook
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.