Write a Python program which will read data for several students from a text file and create a list of lists to store that data. The data must be read from a text file named “Lab11.txt”. Each line in the text file contains the first name, last name, techid, number of credits earned, and number of quality points earned for a single student. The individual items of data on a line are separated by one or more spaces. You can see sample data in the D2L file “Lab11.txt”.

Lab11.txt looks like:
Max Medium 12345678 58 152
Jane Johnson 87654321 78 201
Bill Bupkiss 23456789 29 29
Nate Newby 98765432 0 0
Harold Humphries 11223344 43 160
Carol Cramer 22334455 102 400
Alvin Adams 33445566 67 120
Fred Frederick 44556677 81 250
Phillip Parker 55667788 44 168
Sam Spade 24681357 16 30

For each line that you read in, you are to split it apart and create a list of the individual items. You should also convert the number of credits and number of quality points to integers within this list. These individual lists are then to be concatenated into a list of lists. For example, the composition of your final data structure should be similar to what is shown below.

[[‘Max’,’Medium’,’12345678’,58,152],[‘Jane’,’Johnson’,’87654321’,78,201],…[‘Sam’,’Spade’,’24681357’,16,30]]

Once you get your list constructed, print it so that I can verify that you’ve completed this part. Then go through your list and compute and output the gpa for each student in turn. Remember that gpa is quality points divided by credit hours.

For this lab, you may use any string or list functions or methods that you wish.

I know how to read in the whole file to a list:
myFile = open("Lab11.txt", "r")
myList = list(myfile)

but I am having trouble splitting each line from the file into another list

if i type
print(myList[0])
it will print the first line

please help with this assignment

Dani AI

Generated

Good starts by (list-comprehension idea) and (clear, commented loop). Below is a compact, robust pattern that builds the list-of-lists, validates each line, converts the last two fields to integers, and prints a formatted GPA while avoiding division-by-zero. It uses a whitespace split that tolerates multiple spaces and reports malformed lines.

import re

students = []
split_ws = re.compile(r'\s+')

with open('Lab11.txt', 'r') as fh:
    for lineno, raw in enumerate(fh, 1):
        line = raw.strip()
        if not line:
            continue
        parts = split_ws.split(line)
        if len(parts) != 5:
            print('line {}: skipping (expected 5 fields)'.format(lineno))
            continue
        first, last, techid, credits_s, qpoints_s = parts
        try:
            credits = int(credits_s)
            qpoints = int(qpoints_s)
        except ValueError:
            print('line {}: numeric conversion failed'.format(lineno))
            continue
        students.append([first, last, techid, credits, qpoints])

print(students)

for first, last, techid, credits, qpoints in students:
    if credits:
        gpa = qpoints / float(credits)
        print('{} {} ({}): GPA = {:.2f}'.format(first, last, techid, gpa))
    else:
        print('{} {} ({}): GPA = N/A (0 credits)'.format(first, last, techid))

Notes and troubleshooting

  • re.split(r'\s+') handles multiple spaces reliably; unpacking makes intent explicit. This expands on 's and ’s approaches while adding validation and clear error messages.
  • Keep the techid as a string (leading zeros are significant). Convert only the credit and quality-point fields.
  • Handle zero-credit rows explicitly (division-by-zero). Decide whether to show "N/A" or a numeric value.
  • If input can contain floats for points/credits, use float() instead of int().
  • If a compact comprehension is preferred once parsing/validation is settled, the final validated list can be transformed with a comprehension, but validation is easier to reason about in a small loop first.

Recommended Answers

All 3 Replies

just something to start with:

data_list = [line.split() for line in myFile.readlines()]

One step further:

data = ''' Max Medium 12345678 58 152
Jane Johnson 87654321 78 201
Bill Bupkiss 23456789 29 29
Nate Newby 98765432 0 0
Harold Humphries 11223344 43 160
Carol Cramer 22334455 102 400
Alvin Adams 33445566 67 120
Fred Frederick 44556677 81 250
Phillip Parker 55667788 44 168
Sam Spade 24681357 16 30 '''

import pprint

data_list = [[int(item) if len(item)<=3 and item.isdigit() else item for item in line.split()] for line in data.split('\n')]

pprint.pprint(data_list)

Using a oneliner seems to be very pythonic, but may be hard to comprehend for mere mortals. So here is an alternative with comments to help you:

# each line has these space separated data
# first last ID credit-hours quality-points 
raw_data = ''' Max Medium 12345678 58 152
Jane Johnson 87654321 78 201
Bill Bupkiss 23456789 29 29
Nate Newby 98765432 0 0
Harold Humphries 11223344 43 160
Carol Cramer 22334455 102 400
Alvin Adams 33445566 67 120
Fred Frederick 44556677 81 250
Phillip Parker 55667788 44 168
Sam Spade 24681357 16 30 '''

fname = "lab11.txt"
# write the test file out
with open(fname, "w") as fout:
    fout.write(raw_data)

# read the test file back in and process
with open(fname, "r") as fin:
    mylist = []
    for line in fin:
        temp_list = line.split()
        # convert credit-hours and quality-points to integers
        # these are at index 3 and 4 in the list
        temp_list[3] = int(temp_list[3])
        temp_list[4] = int(temp_list[4])
        mylist.append(temp_list)

# show result
import pprint
pprint.pprint(mylist)        

'''
[['Max', 'Medium', '12345678', 58, 152],
 ['Jane', 'Johnson', '87654321', 78, 201],
 ['Bill', 'Bupkiss', '23456789', 29, 29],
 ['Nate', 'Newby', '98765432', 0, 0],
 ['Harold', 'Humphries', '11223344', 43, 160],
 ['Carol', 'Cramer', '22334455', 102, 400],
 ['Alvin', 'Adams', '33445566', 67, 120],
 ['Fred', 'Frederick', '44556677', 81, 250],
 ['Phillip', 'Parker', '55667788', 44, 168],
 ['Sam', 'Spade', '24681357', 16, 30]]
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.