python使用列表理解从CSV读取特定的行 [英] python reading specific lines from CSV using list comprehension

查看:340
本文介绍了python使用列表理解从CSV读取特定的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



假设我有一个CSV文件,文件被<$ c $分开c> tab ,第三个列可以是a,b或c。我想有一个列表理解(或一个生成器,无所谓),它将只返回文件中选择第一列的那些行

语法错误:

  lines = [tmp = line.rstrip()。split(separator_column)for line in source if tmp [ 2] =='a'] 

是否有可能以更为pythonic的方式一个for循环?所谓的更多pythonic方式正在与C的速度 - 他们比基本的Python指令更快 - 这就是为什么我问。 p>使用 csv module:

 导入csv 
以open(your / file.csv,...)作为源代码:
reader = csv.reader(source,delimiter ='\ t')
selection = [row for reader in row if [2] =='a']


Is it possible to make python read only chosen lines from a file?

Let's say I've got a CSV file, file is separated by tab and the third column is either 'a', 'b' or 'c'. I would like to have a list comprehension (or a generator, doesn't matter) which would return only those lines in the file which have chosen first column

The following throws a syntax error:

lines = [tmp = line.rstrip().split(separator_column) for line in source if tmp[2] == 'a']

Is it possible to do it in a more pythonic way than just a for-loop? So called more pythonic ways are working with the speed of C - they're faster than basic Python instructions - that's why I ask.

解决方案

Use the csv module:

import csv
with open("your/file.csv", ...) as source:
    reader = csv.reader(source, delimiter='\t')
    selection = [row for row in reader if row[2] == 'a']

这篇关于python使用列表理解从CSV读取特定的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆