簡體   English   中英

在一定條件下遍歷python中的CSV文件

[英]Iterating through CSV file in python with certain conditions

所以我試圖遍歷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:不可排序的類型:函數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不成立,則意味着它是有效的日期結構,您可以將其附加到列表中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM