快速打开和关闭csv?

时间:2013-06-25 18:30:10

标签: python csv for-loop generator yield

我正在使用python中的程序将csvs转换为列表列表。它为不同的文件多次这样做,所以我把它变成了一个函数。我没有遇到过这个错误,但我担心这是最pythonic /最聪明/最快的方式,因为这些是巨大的csvs。

import csv

searchZipCode = #there's a zip code here
zipCoords = #there's a file here

def parseFile(selected):
    with open(selected) as selectedFile:
            selectedReader = csv.reader(selectedFile, delimiter=',')
            for row in selectedReader:
                    yield row

def parseZips():
    return parseFile(zipCoords)

zips = parseZips()
for row in zips:
    if row[0] == searchZipCode:
            searchState = row[1]
            searchLat   = row[2]
            searchLong  = row[3]
            print searchState 

基本上,我想知道为什么for row必须重复两次。有没有更优雅的解决方案?

1 个答案:

答案 0 :(得分:1)

您可以在阅读行时进行比较,而不是屈服然后迭代。

def findZip(selected, search):
    results = []
    with open(selected) as file:
        handle = csv.reader(file, delimiter=',')
        for row in handle:
            if row[0] == search
                results.append(row[1:4])
    return results

如果你想进一步优化它,你可以在找到匹配后突破循环,前提是只有一个匹配。

def findZip(selected, search):
    with open(selected) as file:
        handle = csv.reader(file, delimiter=',')
        for row in handle:
            if row[0] == search
                return row[1:4]