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
# define filename as a constant
DATA_FILE= 'students.csv'
NUMBER_OF_STUDENTS = 20

def readDataFromFile():  
    # create empty arrays
    names = [""] * NUMBER_OF_STUDENTS
    marks = [0] * NUMBER_OF_STUDENTS
 
    # open file for reading
    f=open(DATA_FILE, 'r')
 
    for line in range(NUMBER_OF_STUDENTS):
        # decode each line from file
        data = f.readline()
        data = data.strip('n')
        data = data.split(',')
 
        # insert data into arrays
        names[line] = data[0]
        marks[line] = int(data[1])
 
    f.close()
  
    return names, marks
 
#MAIN PROGRAM
names, marks= readDataFromFile()
print(name, mark)

Method 2 (Pythonic)

  • This method appends data onto lists
  • The file is closed automatically when the with loop completes
# define filename as a constant
DATA_FILE= 'students.csv'

def readDataFromFile():  
    # create empty lists
    names = []
    marks = []
 
    # open file for reading
    with open(DATA_FILE, 'r') as f:
        for line in f.readlines():

            # decode each line from file
            data = line.strip('n')
            data = data.split(',')
 
            # add data to lists
            names.append(data[0])
            marks.append(int(data[1]))
 
    return names, marks
 
#MAIN PROGRAM
names, marks= readDataFromFile()
print(name, mark)