Search⌘ K
AI Features

Solution Review: Extracting all the Students With Marks

Explore how to extract student names and their marks from a text file by using Python's file handling, loops, and string manipulation methods. Learn to convert data types, aggregate marks, and conditionally select students based on total scores.

We'll cover the following...

Solution

Python 3.5
def student_names(filename):
mylist = []
with open(filename) as f:
for line in f:
k = line.split(' : ')
myval = []
for num in k[1].split():
num = int(num)
myval.append(num)
total = sum(myval)
if (total > 10):
mylist.append(k[0])
return mylist
filename = 'test.txt'
result = student_names(filename)
print(result)

Explanation

The first thing we need to do is read the text file using the open command. Observe this in line 4 of the above code. Next, at line 5, we can use a for loop to traverse over the contents of the text file.

Note: ...