Question

In: Computer Science

Python, filing and modules Modify the driver to write the statistics to a file named employee-stats.txt...

Python, filing and modules

Modify the driver to write the statistics to a file named employee-stats.txt rather than to the console.

driver.py code:

from employee import Employee
employees = []
# Load an employee object for each employee specified in 'employees.txt' into the employees list.

employee.txt

Jescie Craig VP 95947

Marny Mckenzie Staff 52429

Justin Fuller Manager 72895

Herman Love VP 108204

Hasad Wilkins Staff 96153

Aubrey Eaton Staff 76785

Yvonne Wilkinson Staff 35823

Dane Carlson Manager 91524

Emma Tate Staff 72691

Bryar Bonner Manager 48754

Allegra Jefferson Manager 93610

Richard Stokes Manager 78085

Kimberley Reese Staff 80363

Christian Collins Staff 48864

Colette Casey Staff 27617

Eagan Duran Manager 82666

Aladdin Nash Manager 50925

Jeremy Johnson Staff 58550

Lillith Dawson Manager 59160

Clinton Santos Staff 37320

Tanner Workman Staff 68775

Ashely Mcgee Manager 70635

Blake Peters Manager 44196

Judah Beasley Staff 63186

Alexis Lindsay Staff 36208

Audra Randall Manager 89997

Edward Pope Staff 66393

Jamalia Mccarty Manager 46497

Elvis Rutledge Staff 41969

Paloma Moody Staff 47076

Dominic Long Staff 44557

Candace Moss Manager 85314

Clinton Hardy Staff 56247

Sara Dominguez Manager 62829

Yardley Crawford Manager 89149

Ahmed Hendricks Staff 65129

Fletcher Freeman Staff 34221

Rhiannon Horton Staff 51563

Reagan Hunter Manager 98812

Harper Mason Staff 57284

Owen Crawford Manager 95506

Lois Melendez Staff 72098

Abraham Pugh Staff 32891

Hiroko Hood Staff 60979

Cathleen Horn Manager 75033

Kim Hanson Manager 40919

Shad Contreras Manager 95000

Ezekiel Estes Staff 73942

Liberty Rodgers Staff 39964

Ayanna Gentry Staff 57357

Cassidy Sullivan Manager 49648

Leonard Dillard Staff 53930

Dylan Spencer Staff 72950

Hunter Mckay Staff 68908

Hyacinth Olson Manager 93401

Tanya Bryant Manager 76784

Lucian Suarez Staff 28799

Liberty Garner Staff 66861

Wayne Russell Manager 75801

Lesley Hale Staff 48976

Mona Mckee Manager 87712

Gisela Winters Manager 85863

Tad Curtis Staff 20106

Willow Armstrong Manager 70109

Lesley Brock Manager 75828

Rogan Mccullough Staff 36150

Vaughan Wall Manager 70485

Dillon Hayden Staff 69036

Quynn Fisher Staff 87038

Paul Donaldson Staff 76983

Alea Blankenship Manager 59578

Gil Bush Staff 77769

Odessa Hopper Staff 59715

Galvin Clayton Manager 89641

Ila Zamora Manager 33256

Frances Donovan Manager 81614

Latifah Charles Manager 38059

Jameson Wiley Staff 65428

Cameran Mccall Staff 22922

Cameron Avery Manager 39209

Riley Tillman Staff 34452

Quin Cox Staff 49874

Hayfa Gamble Staff 57834

Whilemina Mccall Staff 50688

Josiah Chandler Staff 64149

Logan Lindsey Staff 77778

Elaine Bullock Manager 36552

Heather Lucas Manager 78369

Carlos Hamilton Staff 47046

# open the file in read mode
file = open('employees.txt')
line = file.readline()

# loop continues till it reach the end of file
while line:
data = line.strip().split(' ')
employees.append(Employee(data[0],data[1],data[2],int(data[3])))
line = file.readline() # read the next line
# close the file
file.close()

file = open('employee-count.txt','w')

max_employee=employees[0]
min_employee=employees[0]
totals={}
counts={}


for i in range(len(employees)):
#Check for maximum salary
if(employees[i].salary>max_employee.salary):
max_employee=employees[i]
#Check for minimum salary
if(employees[i].salary<min_employee.salary):
min_employee=employees[i]
if(employees[i].rank in totals):
totals[employees[i].rank]+=employees[i].salary
counts[employees[i].rank]+=1
else:
totals[employees[i].rank]=employees[i].salary
counts[employees[i].rank]=1
  
print("Maximum Salary:",max_employee)
print("Minimum Salary:",min_employee)
print("Rank\tAverage Salary")
for k in totals.keys():
avg=totals[k]/counts[k]
st="{0:.2f}".format(avg)
print(k+"\t"+st)

employee.py

class Employee:
""" Represents an employee object.
Invariant:
- Salary is an integer.
"""

def __init__(self, first='John', last='Doe', rank='Staff', salary=10000):
"""Instantiate a new employee object, defaulting to a basic John Doe."""
self.first = first
self.last = last
self.rank = rank
self.salary = salary

def __str__(self):
"""Create a employee string with a simple format."""
return self.last + ', ' + self.first + ': ' + self.rank + ' ($' + str(self.salary) + ')'


if __name__ == '__main__':
print(str(Employee()) == 'Doe, John: Staff ($10000)')
print(str(Employee('Jane', 'Doe', 'Czar', 99999)) == 'Doe, Jane: Czar ($99999)')

Solutions

Expert Solution

PLEASE NOTE : FEEL FREE TO ASK ANY DOUBTS by COMMENTING

  • As of you mentioned in the question, I'm just updating the driver.py
  • If you want me to change anything, Please let me know by commenting.
  • I used comments for better understanding. Comments starts with ' # '
  • Please refer to the screenshot of the code to understand the indentation of the code

Language : Python

IDE : Python IDLE

Input Filename : employee.txt

Output Filename : employee-stats.txt

:::::::::::::::::::::::::::::::::::::::::::: CODE ::::::::::::::::::::::::::::::::::::::::

driver.py

from employee import Employee
employees = []
# Load an employee object for each employee specified in
# 'employees.txt' into the employees list.

# open the file in read mode
file = open('employee.txt','r')
line = file.readline()

# loop continues till it reach the end of file
while line:
data = line.strip().split()
employees.append(Employee(data[0],data[1],data[2],int(data[3])))
line = file.readline() # read the next line

# close the file
file.close()

# open file in write mode to write employee stats
file = open('employee-stats.txt','w')

# to store maximum salaried employee
max_employee=employees[0]

# to store minimum salaried employee
min_employee=employees[0]

# to store employee salaries with particular rank
totals={}
# to store employee count of particular rank
counts={}

# loop to find minimum, maximum and rank totals & counts
for i in range(len(employees)):
#Check for maximum salary
if(employees[i].salary>max_employee.salary):
max_employee=employees[i]
#Check for minimum salary
if(employees[i].salary<min_employee.salary):
min_employee=employees[i]

# find employee rank and update total salaries for rank
if(employees[i].rank in totals):
totals[employees[i].rank]+=employees[i].salary
counts[employees[i].rank]+=1
else:
totals[employees[i].rank]=employees[i].salary
counts[employees[i].rank]=1

# write maximum salary to file with newline at end
file.write("Maximum Salary: "+str(max_employee)+"\n")

# write minimum salary to file with newline at end
file.write("Minimum Salary: "+str(min_employee)+"\n")

# write heading to file with newline at end
file.write("Rank\tAverage Salary\n")

# loop for all ranks
for k in totals.keys():
# calculate average
avg=totals[k]/counts[k]

# create string with 2 decimal point for average
st="{0:.2f}".format(avg)

# write rank and average to file with newline at end
file.write(k+"\t"+st+"\n")

# close file
file.close()

_________________________________________________________________

Employee.py

class Employee:
""" Represents an employee object.
Invariant:
- Salary is an integer.
"""

def __init__(self, first='John', last='Doe', rank='Staff', salary=10000):
"""Instantiate a new employee object, defaulting to a basic John Doe."""
self.first = first
self.last = last
self.rank = rank
self.salary = salary

def __str__(self):
"""Create a employee string with a simple format."""
return self.last + ', ' + self.first + ': ' + self.rank + ' ($' + str(self.salary) + ')'

if __name__ == '__main__':
print(str(Employee()) == 'Doe, John: Staff ($10000)')
print(str(Employee('Jane', 'Doe', 'Czar', 99999)) == 'Doe, Jane: Czar ($99999)')
:::::::::::::::::::::::::::::::::::::::::::: OUTPUT ::::::::::::::::::::::::::::::::::::::::

employee-stats.txt

:::::::::::::::::::::::::::::::::::::: CODE in EDITOR ::::::::::::::::::::::::::::::::::

driver.py

Employee.py

_________________________________________________________________

Dear Friend, Feel Free to Ask Any Doubts by Commenting. ASAP i'll respond when i'm available.

I'm on a critical Situation. Please Do Not Forget To Give A Thumbs UP +1. It will Helps me A Lot.

Thank YOU :-)


Related Solutions

Python program: Write a program that reads a text file named test_scores.txt to read the name...
Python program: Write a program that reads a text file named test_scores.txt to read the name of the student and his/her scores for 3 tests. The program should display class average for first test (average of scores of test 1) and average (average of 3 tests) for each student. Expected Output: ['John', '25', '26', '27'] ['Michael', '24', '28', '29'] ['Adelle', '23', '24', '20'] [['John', '25', '26', '27'], ['Michael', '24', '28', '29'], ['Adelle', '23', '24', '20']] Class average for test 1...
(Javascript) Modify the JavaScript file to implement a function named calculateTotalPrice. At the bottom of the...
(Javascript) Modify the JavaScript file to implement a function named calculateTotalPrice. At the bottom of the file are sample inputs and outputs to test your implementation. /* * The price per ticket depends on the number of tickets * purchased, there are 4 ticket pricing tiers. Given the * number of tickets return the total price, formatted to * exactly two decimal places with a leading dollar sign. * Tier 1: *   Minimum number of tickets: 1 *   Price per...
Write the following Python script: Imagine you live in a world without modules in Python! No...
Write the following Python script: Imagine you live in a world without modules in Python! No numpy! No scipy! Write a Python script that defines a function called mat_mult() that takes two lists of lists as parameters and, when possible, returns a list of lists representing the matrix product of the two inputs. Your function should make sure the lists are of the appropriate size first - if not, your program should print “Invalid sizes” and return None. Note: it...
Using Python. A file exists on the disk named students.txt. The file contains several records, and...
Using Python. A file exists on the disk named students.txt. The file contains several records, and each record contains two fields: (1) the student’s name, and (2) the student’s score for the final exam. Write code that deletes the record containing “John Perz”as the student name. This the code i have so far but it's not working: import os def main(): found=False search='John Perz' student_file = open('student.txt','r') temp_file = open('temp_students.txt','w') name=student_file.readline() score='' while name !='': score=student_file.readline() name=name.rstrip('/n') score=score.rstrip('/n') if name...
In Python: Assume a file containing a series of integers is named numbers.txt and exists on...
In Python: Assume a file containing a series of integers is named numbers.txt and exists on the computer's Disk. Write a program that reads al the numbers stored in the file and calculates their total. - create your own text file called numbers.txt and put in a set of 20 numbers (each number should be between 1 and 100). - Each number should be on its own line. - do not assume that the file will always have 20 numbers...
Write a program that creates an output file named rand_nums.txt. Open the file and write 100...
Write a program that creates an output file named rand_nums.txt. Open the file and write 100 random integers between -50 and +50 (inclusive) to the file. Be sure to handle any file IO exceptions. Remember to close the file. Write a program that opens rand_nums.txt for input. Create two output files pos.txt and neg.txt. Read through the input file, one line at a time, converting each line into an integer (no exception handling, yet). If the number is positive, write...
Write scores of 20 students on a quiz to a file. The file should be named...
Write scores of 20 students on a quiz to a file. The file should be named scores.txt. The scores should be random numbers between 0-10. Next, read the scores from scores.txt and double them and print the scores to screen. c++
Write a python program: There is a file called file 2. File2 is a txt file...
Write a python program: There is a file called file 2. File2 is a txt file and I have written the contents of file 2 below in the exact format it was in notepad. # This comment does not make sense # It is just to make it harder # The job description starts after this comment, notice that it has 4 lines. # This job description has 700150 hay system points\\ the incumbent will administer the spending of kindergarden...
modify code to write the output as an HTML table to a file in the output...
modify code to write the output as an HTML table to a file in the output directory. The file that is saying to work at : SOURCE CODE IN PERL: print "Enter principal amount: "; $P=; while($P<=0) { print "Principal must be positive. Try again: "; $P=; } print "Enter number of times interest is applied in a year: "; $n=; while($n!=12 && $n!=4 && $n!=2 && $n!=1) { print "It must be 12, 4, 2 or 1. Try again:...
In Python. A file concordance tracks the unique words in a file and their frequencies. Write...
In Python. A file concordance tracks the unique words in a file and their frequencies. Write a program that displays a concordance for a file. The program should output the unique words and their frequencies in alphabetical order. Variations are to track sequences of two words and their frequencies, or n words and their frequencies. Below is an example file along with the program input and output: Input : test.txt output : 3/4 1, 98 1, AND 2, GUARANTEED 1,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT