如果文件中的日期是sam,则打印消息

2024-04-20 05:48:04 发布

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

我现在的密码。你知道吗

start = datetime.strptime(startDate, "%d/%m/%Y")
end   = datetime.strptime(endDate,"%d/%m/%Y")

with open("filename.txt", "r") as f:
    alldata = csv.reader(f, delimiter = "|")

    for line in alldata:
        alldataLine = datetime.strptime(line[0], "%d/%m/%Y")
        if alldataLine >= start and alldataLine <= end :
            print("{0} --> {1}".format(line[0], line[1]))

我的文件:

30/12/2015|3990.0
30/12/2015|6190.0
31/12/2015|12304.0
02/01/2016|12054.0
02/01/2016|8720.0
02/01/2016|18104.0

我想要的是,如果我有相同的日期,我想我的程序打印的东西后,最后一个相同的日期。你知道吗

示例:

30/12/2015 - 31/12/2015

30/12/2015 --> 3990.0
30/12/2015 --> 6190.0
"one date"

31/12/2015 -->12304.0
"one date"

我试图比较第[0]行和第[0]行,但它会在每个日期后打印“一个日期”。你知道吗


Tags: 密码datetimedatewithlineopenfilenameone
1条回答
网友
1楼 · 发布于 2024-04-20 05:48:04

使用enumerate并检查前后的行:

with open("filename.txt", "r") as f:
    alldata = f.readlines()
    for i, line in enumerate(alldata):
        alldataLine = datetime.strptime(line.split('|')[0], "%d/%m/%Y")
        if alldataLine >= start and alldataLine <= end :
            print("{0}  > {1}".format(line.split('|')[0], line.split('|')[1]))
        try:
            if line.split('|')[0] == alldata[i - 1].split('|')[0] and line.split('|')[0] != alldata[i + 1].split('|')[0]:
                print("one date")
        except IndexError:
            pass

相关问题 更多 >