Skip to main content
 首页 » 编程设计

Python:在 while 循环中迭代 csv

2024年10月25日13itcoder

我有一个 csv 文件,我试图遍历它并让它仅在其中的时间戳落在指定范围内时才执行某些操作。我正在使用 while 循环来执行此操作,每次我都添加 30 秒,但由于某种原因它只在第一次循环而不是每次添加时遍历 csv(虽然我知道它是成功的完成 while 循环本身)。不过我不确定问题出在哪里。

try: 
    csvfilename = sys.argv[1] 
except: 
    csvfilename = "myCSVfile.csv" 
 
 
csvfile = csv.DictReader(open(csvfilename,'rb'),delimiter=',') 
 
startTime = 1402617311 
endTime = 1419544361 
while startTime < endTime: 
    for line in csvfile: 
        if (startTime + 30) > timeToEpoch(line['EnterTime']) >= startTime: 
            output = calcFunction(line['EnterN'],line['ExitN'],line['user']) 
    startTime = startTime + 30 

这里的每个请求都是使用 csv 模块打印的 csv 文件的几行(为了便于阅读而格式化了一些,名称和我的示例中的差异也是因为我稍微更改了它们):

{ 
'Time Exit': '17:02:04',  
'Duration': '0:02:34',  
'Date': '12/7/14',  
'ExitN': '12/7/14 17:02',  
'PlayerSpace': '1',  
'EnterN': '12/7/14 16:59',  
'Time Enter': '16:59:30' 
} 
{ 
'Time Exit': '17:08:18',  
'Duration': '0:08:46',  
'Date': '12/7/14',  
'ExitN': '12/7/14 17:08',  
'PlayerSpace': '2',  
'EnterN': '12/7/14 16:59',  
'Time Enter': '16:59:32' 
} 
{ 
'Time Exit': '17:06:49',  
'Duration': '0:04:20',  
'Date': '12/7/14',  
'ExitN': '12/7/14 17:06',  
'PlayerSpace': '3',  
'EnterN': '12/7/14 17:02',  
'Time Enter': '17:02:29' 
} 

请您参考如下方法:

当您第一次迭代 csvfile 时,您会耗尽它,因此它永远不会产生更多的值。

您的问题的一个解决方案可能是将所有行复制到一个列表中,该列表可以迭代多次:

startTime = 1402617311 
endTime = 1419544361 
csv_lines = list(csvfile)   # <- 
while startTime < endTime: 
    for line in csv_lines:  # <- 
        if (startTime + 30) > timeToEpoch(line['EnterTime']) >= endTime: 
            output = calcFunction(line['EnterN'],line['ExitN'],line['user']) 
    startTime = startTime + 30