0

我是编码新手,我的程序有问题。我必须从文件中获取销售信息并以某种格式打印出来。这是代码:

#Looping program to read file per line
for line in lines:
    # Formatting line to read later
    line = line.strip().split(',')
    year = line[0]
    year = int(year)
    month = line[1]
    month = int(month)
    day = line[2]
    day = int(day)
    linePoint = date(year, month, day)

    cost = line[3]
    cost = float(cost)

    #Finding the lines within the start and end date
    if (linePoint >= startDate) and (linePoint <= endDate):
        printcost = (cost / 100)
        printcost = int(printcost)

        print "%s.%s.%s" % (startYear, startMonth, startDay)
        print "0%s:" % printNum,  "*" * printcost

        newcost = newcost + cost
        printNum += 1

当我使用%s.%s.%s它在销售上方打印日期时,我希望它每月在另一个打印报表上方打印一次,并且能够在一个月结束后增加它。同样在print "0%s:" % printNum, "*" * printcost声明中,我希望它只在前 9 天打印零。

本质上我的问题是我如何在 Python 中运行某些东西一定次数,但次数取决于用户并与日期相关,为了做到这一点,计算机需要能够识别日期。抱歉含糊不清。

4

2 回答 2

1

如果您希望输出是,'01', '02', ..., '10', '11', ...那么您要使用的格式是:

print "%02d" % printNum

至于在每个新月开始时打印标题(这就是我阅读问题第一部分的方式,您可以执行以下操作:

old_month = 0
for line in lines:
    # do stuff
    month = whatever...
    if month != old_month:
        # print header here
        old_month = month
    #rest of loop
于 2012-05-16T16:13:31.497 回答
0

我几乎可以肯定这就是你想要的。请注意“%02d”格式说明符,它为您提供前导零,并检查月份是否已通过if month != current_month.

current_month, print_num, new_cost = None, 0, 0

for line in lines:
    fields = line.strip().split(',')
    year = int(fields[0])
    month = int(fields[1])
    day = int(fields[2])
    cost = float(fields[3])

    line_date = date(year, month, day)

    #Finding the lines within the start and end date
    if startDate <= line_date <= endDate:
        if month != current_month:
            print "%s.%s.%s" % (year, month, day)
            current_month = month

        print_cost = int(cost / 100)
        print "%02d: %s" % (print_num,  "*" * print_cost)

        new_cost += cost
        print_num += 1
于 2012-05-17T04:26:55.120 回答