所以我尝试迭代 csv 文件,如下所示:
time date
25:07 40
0:07 3
0:67 1
0:26 -1
-1:26 4
最后我必须生成一个具有适当约束的列表。如果它不在适当的约束中,那么最终不会生成该行。 约束是这样的: 1. 非法时间值结构(不是 HH:MM)和非法时间值(HH < 0 或 HH> 23、MM < 0 或 MM > 59)。 2. 日期值非法(日期 < 1 或日期 > 31)。
这是我尝试过的:
atm_transaction_time_date = []
my_file = open("atm_file_time_date", "r")
reader = (csv.reader(my_file))
header = my_file.readline()
#to check for illegal time
for line in reader:
if ':' not in (line[0]):
continue
elif int(line[0].split(':')[0]) < 0 or int(line[0].split(':')[0]) > 23:
continue
else:
return (line[0].split(':')[0])
if ':' not in (line[0]):
continue
elif int(line[0].split(':')[1]) < 0 or int(line[0].split(':')[1]) > 59:
continue
else:
return (line[0].split(':')[1])
#to check for illegal date
if 0 > int(line[1]) > 31:
continue
else:
return int(line[1])
atm_transaction = (str(line[0]), int(line[1])
atm_transaction_time_date.append(atm_transaction)
my_file.close()
return atm_transaction_time_date
但是还是没用。这是错误消息 错误 TypeError :不可排序的类型: str() < int() 在函数中引发 elif (line[0].split(':')[0] < 0) 或 (line[0].split(':')[0]) > 23:
最佳答案
问题在于这个语句:
int(line[0].split(':')[0] < 0)
您正在更改整个语句的类型,而不仅仅是 line[0].split(':')[0]
应该是:
int(line[0].split(':')[0]) < 0 or int(line[0].split(':')[0]) > 23
从错误日志中,您可以看到您正在将字符串与 int 进行比较,这是不允许的。正如我所见,你犯了一个愚蠢的错误 对于下面的类似语句,正确地写了它:)
这是代码:
import csv
atm_transaction_time_date = []
my_file = open("atm_file_time_date", "r")
reader = (csv.reader(my_file))
header = my_file.readline()
#to check for illegal time
for line in reader:
if ':' not in (line[0]):
continue
elif int(line[0].split(':')[0]) < 0 or int(line[0].split(':')[0]) > 23:
continue
if ':' not in (line[0]):
continue
elif int(line[0].split(':')[1]) < 0 or int(line[0].split(':')[1]) > 59:
continue
if 0 > int(line[1]) > 31:
continue
atm_transaction = (line[0],int(line[1]))
atm_transaction_time_date.append(atm_transaction)
print atm_transaction_time_date
return 语句在这里没有任何意义。没有您正在调用的函数。 continue 语句传递到循环的下一次迭代。因此,如果 if 和 elif 不成立,则意味着它是有效的日期结构,您可以将其附加到列表中。
关于python - 在特定条件下在 python 中迭代 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33186163/