Read from file into array of records

Method 1 (SQA)

  • This method uses “arrays” of a set size and datatype.
  • The file is explicitly opened and closed
  • Program will crash if there are not enough data lines in the file. Additional data lines will be ignored.
from dataclasses import dataclass

DATA_FILE = 'students.csv'
NUMBER_OF_STUDENTS = 4

@dataclass
class Student():
    name: str=''
    mark: int=0

def read_data_from_file(): 
    # create array of default records
    students = [Student() for student in range(NUMBER_OF_STUDENTS)]
 
    # open file for reading
    f=open(DATA_FILE, 'r')
 
    # read data for every student
    for student in range(NUMBER_OF_STUDENTS):
        # read and decode line from file
        line = f.readline()
        line = line.strip('n')
        line = line.split(',')
 
        # insert data into arrays
        students[student].name = line[0]
        students[student].mark = int(line[1])

    # close data file
    f.close()
     
    return students
 
#MAIN PROGRAM
students = read_data_from_file()

for student in students:
    print(student.name, student.mark)
    

Method 2 (Pythonic)

  • This method appends data onto lists
  • The file is closed automatically when the with loop completes
from dataclasses import dataclass

DATA_FILE = 'students.csv'

@dataclass
class Student():
    name: str=''
    mark: int=0
    
def read_data_from_file():  
    # create empty list
    students = []
  
    # open file for reading
    with open(DATA_FILE, 'r') as f:
        # go through every line of data
        for line in f.readlines():
 
            # decode the line 
            line = line.strip('n')
            line = line.split(',')
  
            # create and add record to list
            name = line[0]
            mark = int(line[1])
            new_student = Student(name, mark)
            students.append(new_student)
  
    return students
  
#MAIN PROGRAM
students = read_data_from_file()

for student in students:
    print(student.name, student.mark)