Looping over a text file list with python

后端 未结 5 1392
予麋鹿
予麋鹿 2021-01-29 10:16

EDIT: Have updated post for better clarity, no answers have yet to help!

Alright, so my assignment is to take a text file, that would have 4 entries per line, those bein

相关标签:
5条回答
  • 2021-01-29 10:28

    Well, I think, you probably want data2 = [word.rstrip("\n") for word in tmp], but without seeing sample input and desired output it's hard to tell.

    Also,

    first[2]=(int(first[2]))
    first[3]=(int(first[3]))
    initialHours = first[2]
    payRate = first[3]
    

    Could be:

    initialHours = int(first[2])
    payRate = int(first[3])
    

    But you'd also need to change other references to first[2]

    Finally, I'd change

    if os.path.isfile(fileQuestion) == True:
    file = open('emps', 'r')
    data = file.readlines()
    for tmp in data:
    

    to:

    if os.path.isfile(fileQuestion) == True:
    with open('emps', 'r') as myfile:
        for tmp in myfile:
    

    This ensures that the file gets closed properly (your code doesn't close it), and iterates directly through the file, rather than using readlines() which needlessly reads the entire file to memory before doing enything else. Note that file is a python builtin, so a bad choice of variable name.

    0 讨论(0)
  • 2021-01-29 10:29
    import os.path
    import sys
    #fileQuestion = input("What is the name of your file?: ")
    fileQuestion = "Testfile.txt"
    heading1 = "{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name",   "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay")
    heading2=    "=============================================================================================================="
    
    print(heading1)
    print(heading2)
    
    if os.path.isfile(fileQuestion) == True:
        file_handle = open(fileQuestion, 'r')
    #file = open('emps', 'r')
    #data = file.readlines()    I would't go for readline here
    
    #file_handle2 = open('outupt.txt')
    total_gross_pay = 0
    number_of_employees = 0
    average_gross_pay = 0
    total_overtime = 0
    standard_working_hours = 40
    
    for i in file_handle:
        data = i.rstrip().lstrip().split()
    
        #print (data)
        first_name, last_name, hours, payrate = data
    
        hours = int(hours)
        payrate = int(payrate)
        basic_pay = hours * payrate
    
        if(hours > standard_working_hours):
            overtime = hours - standard_working_hours
            overtime_premium = overtime * payrate
            gross_pay = overtime_premium + basic_pay
    
        else:
            overtime = 0
            gross_pay = basic_pay
    
        total_overtime += overtime
        total_gross_pay += gross_pay
        number_of_employees += 1
    
        print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format(first_name, last_name, str(hours), str(payrate), str(overtime), str(gross_pay)))
    
    print('\n')
    print("Total Gross Pay:   ",total_gross_pay)
    print("Average Gross Pay: ",total_gross_pay/number_of_employees)
    print("Total overtime:    ",total_overtime)
    
    0 讨论(0)
  • 2021-01-29 10:36

    You are using these lines:

    data = file.readlines()
    for tmp in data:
    

    which already splits your data into lines, and iterates through them. That means that this line [data2= [word.rstrip("\n") for word in data]] is setting data2 to be the first line EVERY TIME, which renders the original for loop useless.

    Try instead:

    tmp = tmp.split()
    

    which will split each line as you iterate, you can now call tmp as a list, like you called first except it will reflect the values for each line.

    You could also change your original for loop to:

    for tmp in file:
    

    since file objects in python are generators that yield each line (this saves you some memory space)

    0 讨论(0)
  • 2021-01-29 10:38

    I found the duplicate, and think some people treat rude ;/ Just not focus on pragmatic problems of programmers but on good rules of Stack in bad way :(

    Here is my complete answer for your problem:

    1) First of all, you must remember that ident is used against code block's brackets known from another landuages.

    I reformatted your code remember that all of lines should have extra spaces at the beginning when you pase it here ;)

    2) like it was said:

    first = word.split()
    

    fix "not changing" of lines in loop.

    3) Total overtime hours have hardcoded number:

    heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", overHours)
    

    Also, overHours(All?) should be not "zeroed" in 'else' block in loop. You must initialize it before loop.

    I change some other places i.e. some hardcoded ints, maybe it not ideal and in your style, but you have code with my fixes below...

    Best, if you use GitHub or Bitbucket or another repo accesible by web, because you help to contribute if you want it, and also - yourself, to find all the changes which was done. And then, just ask here to help in extremely unknown problems. In the begging of learning it is always hard to find out, but later - you could achieve more!

    Here is code after my changes:

    from os.path import isfile as isFileExsist
    import sys
    
    filePath = input("What is the name of your file?: ")
    
    while isFileExsist(filePath) == False:
        pos = ['y', 'Y', 'yes', 'Yes']
        neg = ['n', 'N', 'no', 'No']
        answer = input("File not found! Do you want to start again? (y-yes/n-no)")
        if answer in neg:
            exit("Bye!")
        elif answer in pos:
            filePath = input("What is the name of your file?: ")
            continue
        else:
            print("Not sure what is the answer. Try again!")
            continue
    
    file = open(filePath, 'r')
    data = file.readlines()
    
    print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name",   "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay"))
    print("==============================================================================================================")
    
    overHoursAll = 0
    grossPayAll = 0
    count = 0
    
    for line in data:
        words = line.split()
    
        lastName = words[0]
        firstName = words[1]
        initialHours=(int(words[2]))
        payRate =(int(words[3]))
    
        if initialHours > 40:
            regHours = 40
            overHours = initialHours - 40
    
            regPay = payRate * regHours
            otPay = overHours * (payRate * 1.5)
            grossPay = regPay + otPay
        else:
            regHours = initialHours
            overHours = 0
    
            grossPay = initialHours * payRate
    
    
        grossPayAll += grossPay
        overHoursAll += overHours
    
        # heading3
        print("{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}{5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay))
        # space heading
        print("               ")
    
    # overall stats
    print("{0:15s}{1:21.2f}".format("Total Gross Pay", grossPayAll))
    print("{0:15s}{1:19.2f}".format("Average Gross Pay", grossPayAll / len(data)))
    print("{0:15s}{1:16d}".format("Total Overtime Hours", overHoursAll))
    

    Best regards, I am sorry for my English.

    0 讨论(0)
  • 2021-01-29 10:49

    try these changes:

    totothrs = 0
    totgross = 0.0
    employees = 0
    for tmp in data:
        employees += 1
        fname, lname, rate, hrs = tm.split()
        hrs = int(hrs)
        rate = float(rate)
        othrs = 0
        if hrs > 40:
            othrs = hrs - 40
            hrs = hrs - othrs
    
        totothrs += othrs
        gross = rate * hrs + (1.5*rate)*othrs
        totgross += gross
        heading3= "{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}   {5:24.2f}".format(firstName, lastName, hrs, rate, othrs, gross)
        print heading3
    
    spaceHeading = "       "
    heading4= "{0:15s}{1:21.2f}".format("Total Gross Pay", totgross)
    heading5= "{0:15s}{1:19.2f}".format("Average Gross Pay", (totgross/employees)
    heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", totothrs)
    
    print heading4
    print heading5
    print heading6
    

    Note: you dontneed to define the "headingN"'s you can just print them

    0 讨论(0)
提交回复
热议问题