简体   繁体   中英

Reading data from a file, Splitting it into a list, then taking that data and putting it into a function

I must take a file called employees.txt and pull the names and the amount of hours each person worked. Put that number of hours into a function and have the function return a calculation of hours times an hourly rate of $15.25.

This is what the file contains for data

John Doe,40
Sally Buck,45

This is what I have for code

raw_data = []
with open("employees.txt") as fo:
    for line in fo:
        row = line.split()
        if not row:
            continue
        name = row[0]
        hours = row[1]
        raw_data.append(name, hours)
    def grosspay(hours):
        pay = 0
        hours = row[1]
        hours * float(15.25) = int(pay)
        return pay

I am asking for clarification on reading the file and putting the hours into the function correctly. I can do the rest, I just want to ensure I am doing the part of reading the file, splitting it into a list, and then using that data from the list to find my answer using a function.

So far, there are no errors with my code. I am asking if my process of reading the file, splitting it into a string, then taking that number of hours and using it in the function is correctly done.

You can implement the same in a simple way.

raw_data = []
# defining the function to calculate pay
def grosspay(hours):
        return "$"+str(int(hours) * float(15.25))

print(f'{"Name":30}{"Pay"}')

with open("employee.txt", "r") as f:
    # reading a file line-by-line
    for i in f.readlines():
        # splitting name and work hours
        x = i.split(",")
        print(f'{x[0]:30}{grosspay(x[1])}')
        # appending name and pay to raw_data
        raw_data.append((x,[0],grosspay(x[1])))

Output:

Name                          Pay
John Doe                      $610.0
Sally Buck                    $686.25

Alternative with pandas

import pandas as pd
# reading a file
df = pd.read_csv("dummy.txt", sep=",",names=["Name", "Hours"])
# calculating pay
df["pay"] = df.Hours.apply(lambda x: '$'+str((int(x) * float(15.25))))
# dropping Hours column
df.drop(["Hours"], axis = 1, inplace=True)
# if you want to save in file
df.to_csv("pay.csv")
print(df)

Output:

         Name      pay
0    John Doe   $610.0
1  Sally Buck  $686.25

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM