Just a few more explorations using a Python class to mimic a C Structure or Pascal Record. Loading the record from a csv type data file, displaying the data and sorting and searching the data in various ways.
The Employee Class Record Revisited
Ene Uran commented: helpful +12
'''Class_StructEmp2_file.py
mimic a C Structure or Pascal Record using a class
load the data from a csv type file like this:
John Q. Johnson,computer research,3500
Loyd Tetris,Human Resources,6000
Mark Marksman,external development,4800
tested with Python27 and Python32 by vegaseat
'''
class Employee():
"""
mimics a C Structure or Pascal Record
"""
def __init__(self, name, dept, salary):
self.name = name
self.dept = dept
self.salary = salary
def by_last_name(record):
"""
helper function to sort by last name
assume names are "first middle last"
"""
return record.name.split()[-1]
def by_department(record):
"""
helper function to sort by department case-insensitive
"""
return record.dept.lower()
# load the data file
fname = "employee_data.txt"
with open(fname, "r") as fin:
employee_data = fin.readlines()
record_list = []
for line in employee_data:
line = line.rstrip()
#print(line, type(line), line.split(',')) # test
name, dept, salary = line.split(',')
#print(name, dept, salary) # test
record_list.append(Employee(name, dept, salary))
print("Employee names:")
# explore the record_list by instance
for emp in record_list:
print(emp.name)
print('-'*35)
print("Employee names sorted by last name:")
# sort the records by last name using a helper function
for emp in sorted(record_list, key=by_last_name):
print(emp.name)
print('-'*35)
print("High paid employees:")
# list the folks that get more than $4000 salary per month
for emp in record_list:
if float(emp.salary) > 4000:
print("%s gets more then $4000 a month" % emp.name)
print('-'*35)
print("Sorted by department:")
# sort the records by case insensitive department name
for emp in sorted(record_list, key=by_department):
print("%s works in %s" % (emp.name, emp.dept))
'''result -->
Employee names:
John Q. Johnson
Loyd Tetris
Mark Marksman
-----------------------------------
Employee names sorted by last name:
John Q. Johnson
Mark Marksman
Loyd Tetris
-----------------------------------
High paid employees:
Loyd Tetris gets more then $4000 a month
Mark Marksman gets more then $4000 a month
-----------------------------------
Sorted by department:
John Q. Johnson works in computer research
Mark Marksman works in external development
Loyd Tetris works in Human Resources
'''
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.