This method takes a text file of my work schedule and parses it. It works, but is kind of kludgey, and I'm looking for feedback and suggestions. My first attempt at a file parser, and my first look at Python (I have dabbled in Java/Android and JavaScript). I'm hoping that between the pseudocode and the comments it will be clear what is going on.
Pseudocode:
def read_body(): f = open('file') tempList = [] d = custom data object() for line in f: if line not empty line: if begins with a macron: #denotes new day in the file prepare new/empty data object for line in f: split line for whitespace if line not empty line if line is work log it in data object else its another activity if pay value, also log it elif begins with an equal sign: #denotes end of day else: clean up f.close()
Full Code (it works):
macron = '¯' equalSign = '=' underscore = '_' def read_body(path, month_year): '''Reads schedule detail text file and generates pairing data objects for each work day. path: file to open 'monthYEAR.txt' date: MonthYEAREMPNO (month, year, employee number) from file header ''' f = open(path) tempList = [] d = WorkDay() for line in f: tempList = line.rsplit() if len(tempList) > 0: if macron in tempList[0]: #begin work day #prepare new data object d.clear() d.month_year(month_year) for line in f: tempList = line.rsplit() if len(tempList) > 0: if isWorkingDay(tempList[0]): #parse tempList[1] date block MM/dd/YYYY d.activity_name(tempList[0]) d.date_of_month(tempList[1]) line = f.next() tempList = line.rsplit() d.hours_worked(tempList[1]) d.pay(tempList[3]) break else: #is other activity (sick, off, vacation, etc), log date/time/pay d.activity_name(tempList[0]) #tempList[0] failed isWorkingDay(), so just print. Human readable string for line in f: if underscore in line: break elif 'Credit:' in line: d.pay(line[8:12]) break elif equalSign in tempList[0]: #end work day #drop activity object in "write to db" queue add_to_db(d) else: '''end of file, clean up partial data objects. necessary because schedule text file ends with a macron''' #discard d if empty, raise error if non-complete, write to db if complete pass f.close()