The line:
print data.read ()
consumes all input from the file and positions the file pointer at the end of the file. Subsequent reads will return an empty string, which signifies the end of the file.
I suggest that you use a for loop to iterate over the lines in your file. Also, because the lines are comma separated, you could use the csv
module to assist with splitting the lines into separate fields:
import csv
def loadCourseCatalogue ():
all = {}
with open("catalogue.txt") as data:
for row in csv.reader(data):
all['course'] = row[0]
# extract other fields into all
return all
However, this will overwrite the values in the dictionary all
as each line is processed. Instead you can use course code as a key in the dictionary, and add the rest of the data from each list to its value (also a dictionary). So aim for this data structure:
catalogue = {
'CS1P': {'credits': 20,
'timeday': [('Monday', 14),
('Monday', 15),
('Wednesday', 12),
('Friday', 12)]},
'CS2A': {'credits': 40,
'timeday': [('Monday', 10), ('Monday', 11), ('Thursday', 12)]},
#etc,
}
With this data structure you can easily lookup the data for a given course:
>>> catalogue['CS1P']
{'credits': 20, 'timeday': [('Monday', 14), ('Monday', 15), ('Wednesday', 12), ('Friday', 12)]}
Here's some code that will create such a dictionary:
import csv
from pprint import pprint
def loadCourseCatalogue(data):
catalogue = {}
for row in csv.reader(data):
course = row[0]
catalogue[course] = {
'credits': int(row[1]),
'timeday': zip(row[2::2], (int(i) for i in row[3::2]))
}
return catalogue
with open('catalogue.txt') as f:
catalogue = loadCourseCatalogue(f)
pprint(catalogue)
For input:
CS1P,20,Monday,14,Monday,15,Wednesday,12,Friday,12
CS2A,40,Monday,10,Monday,11,Thursday,12
The output is:
{'CS1P': {'credits': 20,
'timeday': [('Monday', 14),
('Monday', 15),
('Wednesday', 12),
('Friday', 12)]},
'CS2A': {'credits': 40,
'timeday': [('Monday', 10), ('Monday', 11), ('Thursday', 12)]}}
If you want to know how many credits for a course:
>>> catalogue['CS2A']['credits']
40