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) Write a program that does the following: reads each line from a txt file and...
(PYTHON) Write a program that does the following: reads each line from a txt file and convert it to lowercase counts the number of instances of: the characters 'a', 'e','i','o' and 'u' in the file creates a new file of file type .vowel_profile print outs lines in the file indicating the frequencies of each of these vowels Example input/output files: paragraph_from_wikipedia.txt (sample input) link: https://cs.nyu.edu/courses/fall19/CSCI-UA.0002-007/paragraph_from_wikipedia.txt paragraph_from_wikipedia.vowel_profile (sample output) link: https://cs.nyu.edu/courses/fall19/CSCI-UA.0002-007/paragraph_from_wikipedia.vowel_profile Please help!
use Python datetime module, strftime Write a program that processes the following textfile and prints the...
use Python datetime module, strftime Write a program that processes the following textfile and prints the report shown below. Textfile: Ask the user for the filename and BE SURE TO CHECK THAT IT EXISTS. The file will contain lines which each contain 2 strings (bookTitle and publicationDate) separated by a comma and a space. Note that the title of the book might contain spaces! Example of the textfile: Gone Girl, 5-24-2012 To Kill A Mockingbird, 7-11-1960 Harry Potter and the...
In Python... Write a program that randomly assign participants for a study (use the random module)....
In Python... Write a program that randomly assign participants for a study (use the random module). The program should: Display a message stating its goal Prompt the user to enter Number of participants in the study (sample size) Minimum age of the participants Maximum age of the participants Based on these specifications, randomly assign for each participant: Gender (you can use "1" for Male and "2" for Female) Age The program should calculate and display: Total number of male participants...
Python! Create a program that does the following: Reads a number from the user. Calls a...
Python! Create a program that does the following: Reads a number from the user. Calls a function that finds all the divisors of that number. Calls another function to see if the number 7 is a divisor of the original number. Keeps reading input from the user and calling the function above until the user enters the letter ‘q’. Create 2 functions findDivisors() and lucky7(). Use docstrings to explain what each function does. Use the help() function to output the...
must use python Write a nested for loop that displays the following output using the same...
must use python Write a nested for loop that displays the following output using the same integer from part a:                                                     1                                                 1   2   1                                             1   2   4   2   1                                         1   2   4   8   4   2   1                                     1   2   4   8 16   8   4   2   1                                 1   2   4   8 16 32 16   8   4   2   1                             1   2   4   8 16 32 64 32 16   8   4   2   1                         1   2   4  ...
Module 1 Program Write a complete Java program in a file called Module1Program.java that reads all...
Module 1 Program Write a complete Java program in a file called Module1Program.java that reads all the lyrics from a file named lyrics.txt that is to be found in the same directory as the running program. The program should read the lyrics for each line and treat each word as a token. If the line contains a double (an integer is also treated as a double) it should use the first double it finds in line as the timestamp for...
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...
Write a program in python that reads the elements of a set from the keyboard, stores...
Write a program in python that reads the elements of a set from the keyboard, stores them in a set, and then determines its powerset. Specifically, the program should repeatedly ask the user: Enter one more element ? [Y/N] If the user answers Y then an new element is read from the keyboard: Enter the new element in the set: This cycle continues until the user answers N to the first question. At that point the program shall compute the...
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...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT