快速打开和关闭csv?

2024-10-03 00:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python编写一个程序,将csv转换为列表列表。它为不同的文件做了多次,所以我把它做成了一个函数。我还没有遇到过这样的错误,但我担心这是最具python/最聪明/最快的方式,因为这些都是巨大的csv。你知道吗

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必须重复两次。难道没有更优雅的解决方案吗?你知道吗


Tags: csvin列表forheredefrowthere
1条回答
网友
1楼 · 发布于 2024-10-03 00:22:36

您可以在读取行时简单地进行比较,而不是先产生行,然后进行迭代。你知道吗

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]

相关问题 更多 >