使用Python循环遍历文本文件列表

2024-09-30 14:31:52 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:有更新的帖子为了更好的清晰,没有答案还没有帮助!在

好的,我的任务是取一个文本文件,每行有4个条目,分别是名字,姓,小时,工资率。我将进行一些计算,并将所有这些信息放入python的格式化表中。现在,我已经有了将数据输入到表中的代码,但是它只适用于文本文件中的第一个条目,而且我不能完全使它循环。我真的觉得自己像个白痴,这只是一个简单的解决办法。在

我的输出应该是这样的:

http://i.imgur.com/bIOBqye.png

可以真正使用一些指针来循环并从文本文件的每一行打印数据。下面是我当前代码的外观:

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 = open('emps', 'r')
data = file.readlines()
for tmp in data:

    data2= [word.rstrip("\n") for word in data]
    first = data2[0].split()

    lastName = first[0]
    firstName = first[1]
    first[2]=(int(first[2]))
    first[3]=(int(first[3]))
    initialHours = first[2]
    payRate = first[3]

    if initialHours > 40:
        overHours = initialHours - 40
        regHours = 40
        regPay = payRate * regHours
        otPay = overHours * (payRate * 1.5)
        grossPay = regPay + otPay

    else:
        regHours = first[2]
        grossPay = initialHours * payRate
        overHours = 0



    heading3= "{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}   {5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay)
    heading4= "{0:15s}{1:21.2f}".format("Total Gross Pay", grossPay)
    heading5= "{0:15s}{1:19.2f}".format("Average Gross Pay", grossPay)
    heading6= "{0:15s}{1:16d}".format("Total Overtime Hours", 33)
    spaceHeading = "               "

    print(heading3)
    print(spaceHeading)
print(heading4)
print(heading5)
print(heading6)

请让我知道,如果我没有正确地做这件事或任何事,第一次在这里。谢谢。在


Tags: 数据formatdata条目payfirstprint文本文件
3条回答

好吧,我认为您可能想要data2 = [word.rstrip("\n") for word in tmp],但是如果没有看到示例输入和期望的输出,就很难判断。在

还有

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

可能是:

^{pr2}$

但您还需要更改对first[2]的其他引用

最后,我会改变

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

收件人:

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

这可以确保文件被正确关闭(您的代码不会关闭它),并直接迭代该文件,而不是使用readlines()在执行其他操作之前不必要地将整个文件读入内存。注意,file是一个python builtin,所以变量名的选择是错误的。在

我发现了重复,并且认为有些人对待粗鲁;只是不关注程序员的实际问题,而是以不好的方式关注堆栈的好规则:(

以下是我对您问题的完整答案:

(一) 首先,您必须记住,ident是针对来自另一个语言的代码块的方括号使用的。在

我重新格式化了您的代码请记住,当您在这里输入代码时,所有行的开头都应该有额外的空格;)

2)正如人们所说:

first = word.split()

“不固定”循环中的换行。在

3)总加班时间有硬编码编号:

^{pr2}$

还有,加班(全部?)不应在循环中的“else”块中“归零”。必须在循环之前初始化它。在

我改变了一些其他的地方,也就是一些硬编码的整数,也许这不是理想的和你的风格,但你有代码与我的修复下面。。。在

最好的方法是使用GitHub或Bitbucket或其他可通过web访问的repo,因为如果你愿意,你可以帮助你自己,也可以帮助你自己找到所做的所有更改。然后,在这里请求帮助解决非常未知的问题。在求学的过程中,总是很难发现的,但是以后-你可以获得更多!在

以下是更改后的代码:

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

谨致问候,我为我的英语感到抱歉。在

您正在使用以下行:

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

它已经将数据拆分成行,并在其中迭代。这意味着这行[data2= [word.rstrip("\n") for word in data]]每次都将data2设置为第一行,这使得原来的for循环无效。在

试试看:

^{pr2}$

它将在迭代时拆分每一行,现在可以将tmp作为一个列表调用,就像您调用first一样,但它将反映每一行的值。在

也可以将原始for循环更改为:

for tmp in file:

因为python中的文件对象是生成每一行的生成器(这样可以节省一些内存空间)

相关问题 更多 >