如何遍历tsv文件中的所有行?

时间:2017-07-27 17:44:35

标签: python-3.x

我有一个tsv文件,我想遍历所有行。这是我的代码:

import csv

with open('tsv2.tsv','r') as tsvin:
    tsvin = csv.reader(tsvin, delimiter='\t')
    tsv_file = tsvin

    def non_synonymous_filter(tsv_file):
        non_synonymous_list=[]
        for row in range(len(tsv_file)):
            if "NON_SYNONYMOUS_CODING" in row[index]:
                non_synonymous_list.append(row)

        return non_synonymous_list

    print(non_synonymous_filter(tsv_file))

问题是我收到此错误消息:类型' _csv.reader'的对象没有len()

1 个答案:

答案 0 :(得分:0)

代码中的

tsvin / tsv_file是CSV阅读器,而不是包含文本的列表或数组。我建议阅读这样的行,然后检查你的内部方法:

with open('tsv2.tsv','r') as tsvin:
    for line in csv.reader(tsvin, delimiter='\t'):
        print line

我不清楚你究竟想要什么(比如什么是"索引"?),但也许这个:

non_synonymous_list=[]
with open('tsv2.tsv','r') as tsvin:
    non_synonymous_list = [line for line in csv.reader(tsvin, delimiter='\t') if "NON_SYNONYMOUS_CODING" in line]

返回类似的内容:

[[' NON_SYNONYMOUS_CODING',' 2nd col',' 3rd col']