Question

In: Computer Science

Use PYTHON --Nested Lists and DateTime Module. Write a program that does the following: Reads information...

Use PYTHON --Nested Lists and DateTime Module.

Write a program that does the following:

  • Reads information from a text file into a list of sublists.
    • Be sure to ask the user to enter the file name and end the program if the file doesn’t exist.
    • Text file format will be as shown, where each item is separated by a comma and a space:
      ID, firstName, lastName, birthDate, hireDate, salary
  • Store the information into a list of sublists called empRoster.
    EmpRoster will be a list of sublists, where each sublist contains the information for one employee.
    The birthDate and hireDate in file are strings, but should be stored as objects of type Date.
    Example of EmpRoster list with 2 employees but can be more:
    [   [111,”Joe”, “Jones”, “09-01-1980”,”10-19-1999”, 95000],     \
          [222, “Sam”, “Smith”, “07-10-1956”,, “01-01-2000”, 50000]    ]
  • Print a report that shows the following:
                                                         Employee Roster
    ID   First Name,       Last Name,       Birth Date,        Age,     Hire Date, YrsWorked, Salary,
  • WRITE the following information out to a text file – ask the user what the text file should be named!
    • Employees over 60 years old
    • Employees with salaries above 50000
    • Employees that have worked for the company more than 20 years
  • Example input file:
    111, Joe, Jones, 09-01-1980, 10-19-1999, 95000
    222, Sam, Smith, 07-10-1956, 01-01-2000, 50000
    333, Rick, Robins, 08-01-1960, 08-20-1998, 100000
  • Example report for the sample data:

                                                Employee Roster

ID         First Name        Last Name        Birth Date         Age      Hire Date          Yrs Worked       Salary

111      Joe                   Jones                Sep 1, 1980       39        Oct 19, 1999     21                   95000

222      Sam                  Smith               Jul 10, 1956      63        Jan 1, 2000       20                      50000

333      Rick                  Robins              Aug 1, 1960      59        Aug 20, 1998    22                   100000

  • Example output file:

Employees over 60 years old:
Sam Smith

Employees with salaries above 50000:
Joe Jones

Rick Robins

Employees that have worked for the company more than 20 years

Joe Jones
Rick Robins

Solutions

Expert Solution

EDIT: CODE REFACTORED TO INCLUDE FUNCTIONS:
Below is a screen shot of the python program to check indentation.



Below is the output of the program:
Console output:

Output file(emp_output.txt):


Below is the code to copy:
#CODE STARTS HERE----------------
import os
from datetime import datetime

def read_file(): #Reads filename from input and stores content in empRoster
   empRoster = []
   f_name = input("Enter file name: ")
   if not os.path.exists(f_name): #Check if file exists
      print("File doesnot exist!")
      exit()

   with open(f_name) as f: #Read file
      for line in f.readlines(): #Loop line by line
         new_list = []
         for col in range(len(line.strip().split(", "))):#Loop value by value
            temp_li = line.strip().split(", ")
            if col == 3 or col == 4: #For birth date and hire date, convert str to datetime
               x = datetime.strptime(temp_li[col], '%m-%d-%Y')
               new_list.append(x)
            else:
               new_list.append(temp_li[col])
         empRoster.append(new_list)
   return empRoster #Return emp's list of lists

def calculate(empRoster): #Calculates the employees who are above the given conditions
   f_out = input("\nEnter a file name to output: ")
   with open(f_out, "a+") as ff: #Write output to a file
      ff.write("Employees over 60 years old:\n")
      for emp in empRoster:
         if emp[4] >= 60:
            ff.write(emp[1] + " " + emp[2] + "\n")

      ff.write("Employees with salaries above 50000:\n")
      for emp in empRoster:
         if int(emp[-1]) > 50000:
            ff.write(emp[1] + " " + emp[2] + "\n")

      ff.write("Employees that have worked for the company more than 20 years\n")
      for emp in empRoster:
         if int(emp[-2]) > 20:
            ff.write(emp[1] + " " + emp[2] + "\n")
   print("Output saved to file!")

def number_of_years(empRoster): #Calculates number of years since birth and since hire
   newEmpRoster = [] #Stores new data to a new list
   for line in empRoster:
      newRoster = []
      for col in line:
         if line.index(col) == 3 or line.index(col) == 4: #Adds Age and yrs worked here
            newRoster.append(datetime.strftime(col, '%m-%d-%Y'))
            newRoster.append(int((datetime.now() - col).days / 365))
         else:
            newRoster.append(col)
      newEmpRoster.append(newRoster)
   return newEmpRoster

def print_report(empRoster): #Prints value in empRoster
   print("{:^80}".format("Employee roster"))
   print("{:6}{:15}{:13}{:20}{:5}{:15}{:15}{:15}".format("ID", "First name", "Last name",
                                             "Birth date", "Age", "Hire date",
                                             "Yrs worked", "Salary"))
   for line in empRoster: #Formats output and prints reslt
      print("{:6}{:15}{:13}{:20}{:^5}{:15}{:^15}{:15}".format(*line))

def main():
   empRoster = read_file()
   empRoster = number_of_years(empRoster)
   print_report(empRoster)
   calculate(empRoster)

main()
#CODE ENDS HERE------------------

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...
You are to write a C++ program which does the following: Reads in the size of...
You are to write a C++ program which does the following: Reads in the size of a list of characters. Reads in the list of characters. Prints the list of characters in the opposite order read in. Prints the list of characters in the order read in. Sorts the list. Prints the sorted list. You may assume there will be no more than 1000 characters in the list. (You should use a constant to make this limit easily changeable.) You...
Overview: You will write a python program that will work with lists and their methods allowing...
Overview: You will write a python program that will work with lists and their methods allowing you to manipulate the data in the list. Additionally you will get to work with randomization. Instructions: Please carefully read the Instructions and Grading Criteria. Write a python program that will use looping constructs as noted in the assignment requirements. Name your program yourlastname_asgn5.py Assignment Requirements IMPORTANT: Follow the instructions below explicitly. Your program must be structured as I describe below. Write a Python...
write a python program that reads a sentence and identifies a word from an existing glossary...
write a python program that reads a sentence and identifies a word from an existing glossary and states the meaning of the word
Write a Python program that reads in two times, an earlier time and a later time,...
Write a Python program that reads in two times, an earlier time and a later time, and prints the difference between the two times in minutes as well as in hours/minutes. The format of the time is HH:MMAM or H:MMAM or HH:MMPM or H:MMPM. Also the AM or PM may be in lower case. A sample run of the program is shown below: $ python3 Time.py Enter Earlier Time: 9:36aM Enter Later Time: 6:22PM Number of minutes between 9:36aM and...
Design and write a python program that reads a file of text and stores each unique...
Design and write a python program that reads a file of text and stores each unique word in some node of binary search tree while maintaining a count of the number appearance of that word. The word is stored only one time; if it appears more than once, the count is increased. The program then prints out 1) the number of distinct words stored un the tree, Function name: nword 2) the longest word in the input, function name: longest...
Write a Python program for the following: A given author will use roughly use the same...
Write a Python program for the following: A given author will use roughly use the same proportion of, say, four-letter words in something she writes this year as she did in whatever she wrote last year. The same holds true for words of any length. BUT, the proportion of four-letter words that Author A consistently uses will very likely be different than the proportion of four-letter words that Author B uses. Theoretically, then, authorship controversies can sometimes be resolved by...
Using Python. Write a program that reads a sequence (unknown number of inputs) of integer inputs...
Using Python. Write a program that reads a sequence (unknown number of inputs) of integer inputs and prints the number of even and odd inputs in the sequence. please explain. Thanks
Python 8.17 LAB: Strings of a Frequency Write a program that reads whitespace delimited strings (words)...
Python 8.17 LAB: Strings of a Frequency Write a program that reads whitespace delimited strings (words) and an integer (freq). Then, the program outputs the strings from words that have a frequency equal to freq in a case insensitive manner. Your specific task is to write a function wordsOfFreqency(words, freq), which will return a list of strings (in the order in which they appear in the original list) that have a frequency same as the function parameter freq. The parameter...
Write a Python program that reads a file, input by the user, containing one word/token per...
Write a Python program that reads a file, input by the user, containing one word/token per line with an empty line between sentences. The program prints out the longest word found in the file along with its length.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT