Skip to main content
 首页 » 编程设计

python之帮助解决 Python 循环怪异问题

2025年05月04日10pengyingh

我正在学习 Python 作为我的第二门编程语言(如果不算 HTML/CSS/Javascript,我是第一个真正的语言)。我正在尝试构建一些有用的东西作为我的第一个真正的应用程序——一个 IRC 机器人,当 channel 中发生某些事情时,它会通过 SMS 提醒人们。根据某人的请求,我正在(尝试)建立日程安排偏好,人们可以选择在一天中的 X 和 Y 小时之间不接收警报。

无论如何,这是我遇到问题的代码:

db = open("db.csv") 
for line in db: 
            row = line.split(",")  # storing stuff in a CSV, reading out of it  
            recipient = row[0]     # who the SMS is going to 
            s = row[1]             # gets the first hour of the "no alert" time range 
            f = row[2]             # gets last hour of above 
            nrt = []               # empty array that will store hours 
            curtime = time.strftime("%H")  # current hour 
            if s == "no":           
                    print "They always want alerts, sending email"  # start time will = "no" if they always want alerts 
                    # send mail code goes here 
            else: 
                    for hour in range(int(s), int(f)): #takes start, end hours, loops through to get hours in between, stores them in the above list  
                            nrt.append(hour) 
                    if curtime in nrt: # best way I could find of doing this, probably a better way, like I said I'm new 
                            print "They don't want an alert during the current hour, not sending"  # <== what it says 
                    else: 
                            # they do want an alert during the current hour, send an email 
                            # send mail code here 

我遇到的唯一问题是脚本以某种方式最终只循环遍历其中一行(或类似行),因为我每次只得到一个结果,即使我在 CSV 文件中有多个条目也是如此.

请您参考如下方法:

如果这是一个普通的 CSV 文件,您不应该尝试自己解析它。使用标准库 csv module .

这是文档中的一个简短示例:

import csv 
reader = csv.reader(open("some.csv", "rb")) 
for row in reader: 
    print row