gurehbgui
gurehbgui

Reputation: 14694

read a csv into a list with one command and then read in it

is it possible to read a csv like this:

1,22,5
1,33,9
3,44,5
4,32,5
5,53,5
6,64,5
7,12,7

with one command to a list with the format [(1,22,5),...]?

And how can I search in the list after that to get e.g. all elemente where the first column is a 1?

For example: get all with row1 == 1 will return

1,22,5
1,33,9

Upvotes: 1

Views: 55

Answers (2)

jamylak
jamylak

Reputation: 133634

import csv

with open('data.csv', 'rb') as f:
    rows = [[int(el) for el in row] for row in csv.reader(f)]


>>> rows
[[1, 22, 5], [1, 33, 9], [3, 44, 5], [4, 32, 5], [5, 53, 5], [6, 64, 5], [7, 12, 7]]
>>> [row for row in rows if row[0] == 1]
[[1, 22, 5], [1, 33, 9]]

Upvotes: 2

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136425

It is possible.

import csv
csv_rows = list(csv.reader(sys.stdin))

http://docs.python.org/2/library/csv.html

Upvotes: 1

Related Questions