2016-04-10 81 views
0

我有一个包含csvfiles的编程任务。到目前为止,我只有一个问题,只能从特定行中获取值,这是用户想要查找的行。在Python的csvFile中遍历特定行

当我感到沮丧时,我只是将每列添加到一个单独的列表中,这是非常慢的(列表打印测试时),因为每列都有数百个值。

问题: 期望的行是其索引[0] == user_input的行。我怎样才能获得这些特定的行并忽略其他行?

+0

您可以显示更多的代码。什么是索引[]? –

回答

0

这应该给你一个想法:

import csv 
with open('file.csv', 'rb') as f: 
    reader = csv.reader(f, delimiter=',') 
    user_rows = filter(lambda row: row[0] == user_input, reader) 
0

Python有模块CSV

import csv 
rows=[] 
for row in csv.reader(open('a.csv','r'),delimiter=','): 
    if(row[0]==user_input): 
     rows.append(row) 
0
def filter_csv_by_prefix (csv_path, prefix): 
    with open (csv_path, 'r') as f: 
     return tuple (filter (lambda line : line.split(',')[0] == prefix, f.readlines())) 

for line in filter_csv_by_prefix ('your_csv_file', 'your_prefix'): 
    print (line)