我正在学习Python作为我的第二种编程语言(如果你不算HTML/CSS/Javascript,我的第一个真正的编程语言).我正在尝试构建一些有用的东西作为我的第一个真正的应用程序 - 一个IRC机器人,当通道中发生某些事情时通过短信提醒人们.根据某人的请求,我(尝试)建立调度首选项,人们可以选择不在当天的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
Run Code Online (Sandbox Code Playgroud)
我遇到的唯一问题是以某种方式脚本只会循环遍历其中一行(或类似的东西),因为我每次只得到一个结果,即使我在CSV文件中有多个条目.
小智 9
如果这是常规CSV文件,则不应尝试自行解析.使用标准库csv模块.
以下是文档中的简短示例:
import csv
reader = csv.reader(open("some.csv", "rb"))
for row in reader:
print row
Run Code Online (Sandbox Code Playgroud)
您的程序中至少有两个错误:
curtime = time.strftime("%H")
...
for hour in range(int(s), int(f)):
nrt.append(hour)
# this is an inefficient synonym for
# nrt = range(int(s), int(f))
if curtime in nrt:
...
Run Code Online (Sandbox Code Playgroud)
首先,curtime是一个字符串,而nrt是一个整数列表.Python是强类型的,因此这两者不可互换,并且不会比较相等:
'4' == 4 # False
'4' in [3, 4, 5] # False
Run Code Online (Sandbox Code Playgroud)
此修订后的代码解决了该问题,并且比生成列表和搜索其中的当前小时更有效:
cur_hour = time.localtime().tm_hour
if int(s) <= cur_hour < int(f):
# You can "chain" comparison operators in Python
# so that a op1 b op2 c is equivalent to a op1 b and b op2c
...
Run Code Online (Sandbox Code Playgroud)
上面没有解决的第二个问题是,如果小时数在午夜环绕(例如s = 22和f = 8),你的程序将无法正常运行.
这些问题都不一定与"脚本只能通过其中一条线路循环"有关,但你没有给我们足够的信息来弄清楚为什么会这样.提出问题的一种更有用的方法是发布一个简短但完整的代码片段,其中显示您正在观察的行为,以及示例输入和生成的错误消息(如果有的话)(以及追溯).
你有没有尝试过更简单的东西?只是为了看看Python如何实际读取您的文件:
db = open("db.csv")
for line in db:
print line
Run Code Online (Sandbox Code Playgroud)
您的csv文件的格式可能有问题.例如,当您在Windows环境中打开Unix文件时,就会发生这种情况.在这种情况下,整个文件看起来像单个字符串,因为Windows和Unix有不同的行分隔符.所以,我不知道你的问题的某些原因,但提出要朝这个方向思考.
更新: 你的循环体有多种方式:
s是"no":"They always want alerts, sending email"将被打印.s不会"no"和curtime in nrt:"They don't want an alert during the current hour, not sending"将被打印.s不是"no"而且curtime in nrt是假的(最后一个else):什么都不打印,没有采取任何其他行动.你不应该print在最后一个else分支中放置一些陈述吗?
此外,您的代码段的确切输出是什么?是"They always want alerts, sending email"吗?