python - 在特定条件下在 python 中迭代 CSV 文件

标签 python csv

所以我尝试迭代 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/

相关文章:

python - Gtk-ERROR ** : GTK+ 2. x 检测到符号。不支持在同一进程中使用 GTK+ 2.x 和 GTK+ 3(Kivy 应用程序)

excel - 如何防止excel截断CSV文件中的数字?

Python变量赋值给一个函数

python - 在 Mac 上运行 sugiyama.py 时出现 lxml 错误

python - 如何在 pygame 中调色板交换 Sprite 而不使用后面的矩形

csv - 如何在 Coldfusion 中导入/读取 csv(逗号分隔)文件中的数据

c# - 如何拆分列可能包含逗号的csv

mysql - 如何根据值更新插入时的列

java - 在 Struts2 中将动态数据从 JSP 页面导出到 CSV

python - 在 python 代码中使用 f2py 模块时的问题