Question

In: Computer Science

This is a python file Reads information from a text file into a list of sublists....

This is a python file

  • 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:
    [   [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

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------------------


IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK YOU!!!!!!!!----------


Related Solutions

I have a Python code that reads the text file, creates word list then calculates word...
I have a Python code that reads the text file, creates word list then calculates word frequency of each word. Please see below: #Open file f = open('example.txt', 'r') #list created with all words data=f.read().lower() list1=data.split() #empty dictionary d={} # Adding all elements of the list to a dictionary and assigning it's value as zero for i in set(list1):     d[i]=0 # checking and counting the values for i in list1:     for j in d.keys():        if i==j:           d[i]=d[i]+1 #Return all non-overlapping...
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces...
Write a simple text-formating.cpp file that reads (asks for then reads) a text file and produces another text file in Which blank lines are removed, multiple blanks are replaced with a single blank, and no lines are longer than some given length (let say 80). Put as many words as possible on the same line (as close as possible to 80 characters). You will have to break some lines of the given file, but do not break any words or...
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...
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...
Write an assembly language program that reads move review information from a text file and reports...
Write an assembly language program that reads move review information from a text file and reports the overall scores for each movie as well as identifying the movie with the highest total score. There are four movie reviewers numbered from 1 to 4. They are submitting reviews for five movies, identified by the letters from “A” through “E”. Reviews are reported by using the letter identifying the movie, the review rating, which is a number from 0 to 100, and...
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. In paragraph 1 Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. In pragraph 2 Replace "We" with v"i" This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would...
Could you write a c- program that reads a text file into a linked list of...
Could you write a c- program that reads a text file into a linked list of characters and then manipulate the linked list by making the following replacements 1. Replace all “c” with “s” if followed by the characters “e”, “i” or “y”; otherwise 2. Replace "sh" with ph This is the text to be manipulated: Paragraph1 She told us to take the trash out. Why did she do that? I wish she would not do that Paragraph 2 We...
Solve using PYTHON PROGRAMMING 9. Write a script that reads a file “ai_trends.txt”, into a list...
Solve using PYTHON PROGRAMMING 9. Write a script that reads a file “ai_trends.txt”, into a list of words, eliminates from the list of words the words in the file “stopwords_en.txt” and then a. Calculates the average occurrence of the words. Occurrence is the number of times a word is appearing in the text b. Calculates the longest word c. Calculates the average word length. This is based on the unique words: each word counts as one d. Create a bar...
● Write a program that reads words from a text file and displays all the words...
● Write a program that reads words from a text file and displays all the words (duplicates allowed) in ascending alphabetical order. The words must start with a letter. Must use ArrayList. MY CODE IS INCORRECT PLEASE HELP THE TEXT FILE CONTAINS THESE WORDS IN THIS FORMAT: drunk topography microwave accession impressionist cascade payout schooner relationship reprint drunk impressionist schooner THE WORDS MUST BE PRINTED ON THE ECLIPSE CONSOLE BUT PRINTED OUT ON A TEXT FILE IN ALPHABETICAL ASCENDING ORDER...
Write a C program that Reads a text file(any file)  and writes it to a binary file....
Write a C program that Reads a text file(any file)  and writes it to a binary file. Reads the binary file and converts it to a text file.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT