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

Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file...
Problem: Write a Python module (a text file containing valid Python code) named p5.py. This file must satisfy the following. Define a function named rinsert. This function will accept two arguments, the first a list of items to be sorted and the second an integer value in the range 0 to the length of the list, minus 1. This function shall insert the element corresponding to the second parameter into the presumably sorted list from position 0 to one less...
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...
​​​​Python Create a new file named compute_cost.py. Write your name and date in a comment. Create...
​​​​Python Create a new file named compute_cost.py. Write your name and date in a comment. Create a variable named base_fee and set the value to 5.5. Prompt the user for the zone. The zones can be an integer value from 1 to any value for the zone. Convert the zone to an integer. Display the zone on the SenseHat with a scroll speed of 0.3, make the text blue, and the background yellow. Scroll "The zone is " and the...
Write a Python script that performs brute force to extract a password protected zip file named...
Write a Python script that performs brute force to extract a password protected zip file named sec2.zip. The password is believed to be associated with one of the dictionary word in the 'wordlist.txt file. a) Paste your code here b) What is the password?
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...
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 this PYTHON 3 program assignment, you will find a text file named WorldSeries.txt. This file...
In this PYTHON 3 program assignment, you will find a text file named WorldSeries.txt. This file contains a chronological list of the World Series' winning teams from 1903 through 2018. The first line in the file is the name of the team that won in 1903, and the last line is the name of the team that won in 2018. (Note the World Series was not played in 1904 and 1994. There are entries in the file indicating this.) Write...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT