从CSV读取和过滤列

时间:2016-10-16 07:32:26

标签: python csv

我有一个CSV文件。

有固定数量的列和未知数量的行。

我需要的信息总是在同一行中,但不在同一行。

当第6列的值为17时,我还需要从第0列获取数据。

这是CSV文件中的示例行:

E4:DD:EF:1C:00:4F, 2012-10-08 11:29:04, 2012-10-08 11:29:56, -75, 9, 18:35:2C:18:16:ED,

2 个答案:

答案 0 :(得分:0)

您可以打开文件并逐行浏览。拆分该行,如果元素6有17个字符,则将元素0追加到结果数组中。

f = open(file_name, 'r')
res = []
for line in f:
    L = line.split(',')
    If len(L[6])==17:
        res.append(L[0])

现在你有一个包含你cvs第6列中所有元素的列表。

答案 1 :(得分:0)

您可以使用 csv 模块读取csv文件,并且可以在使用csv reader读取文件时根据需要提供分隔符/方言(或者|或制表符等..)。 csv reader负责为行/记录提供列作为值列表。如果要以cict的形式访问csv记录/行,则可以使用 DictReader 及其方法。

import csv
res = []
with open('simple.csv', 'rb') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        # Index start with 0 so the 6th column will be 5th index
        # Using strip method would trim the empty spaces of column value
        # Check the length of columns is more than 5 to handle uneven columns
        if len(row) > 5 and len(row[5].strip()) == 17:
            res.append(row[0])

# Result with column 0 where column 6 has 17 char length
print res
相关问题