Read from file into parallel arrays
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
DATA_FILE= 'students.csv'
NUMBER_OF_STUDENTS = 4
def read_data_from_file():
# create empty arrays
names = [""] * NUMBER_OF_STUDENTS
marks = [0] * NUMBER_OF_STUDENTS
# open file for reading
f=open(DATA_FILE, 'r')
# read data for every student
for student in range(NUMBER_OF_STUDENTS):
# decode each line from file
line = f.readline()
line = line.strip('n')
line = line.split(',')
# insert data into arrays
names[student] = line[0]
marks[student] = int(line[1])
# close data file
f.close()
return names, marks
#MAIN PROGRAM
names, marks= read_data_from_file()
for student in range(NUMBER_OF_STUDENTS):
print(names[student], marks[student])
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 read_data_from_file():
# create empty lists
names = []
marks = []
# 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(',')
# add data to lists
names.append(line[0])
marks.append(int(line[1]))
return names, marks
#MAIN PROGRAM
names, marks = read_data_from_file()
for student in range(len(names)):
print(names[student], marks[student])