简体   繁体   中英

python reading specific lines from CSV using list comprehension

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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