简体   繁体   English

python使用列表理解从CSV读取特定行

[英]python reading specific lines from CSV using list comprehension

Is it possible to make python read only chosen lines from a file? 是否可以使python只读取文件中选择的行?

Let's say I've got a CSV file, file is separated by tab and the third column is either 'a', 'b' or 'c'. 假设我有一个CSV文件,文件由tab分隔, 第三列是“ a”,“ b”或“ 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? 是否有可能以比仅for循环更Python的方式执行此操作? So called more pythonic ways are working with the speed of C - they're faster than basic Python instructions - that's why I ask. 所谓的更多pythonic方式正在以C的速度工作-它们比基本的Python指令要快-这就是我问的原因。

Use the csv module: 使用csv模块:

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM