user3581242
user3581242

Reputation: 17

Print from specific row of csv file

my csv file has multiple tables in a single file for example

name age gender
n1    10  f
n2    20  m
n3    30  m
city  population 
city1   10
city2   20
city3   30

How can I print from city row to city3 row.using python csv module

Upvotes: 0

Views: 805

Answers (2)

knh170
knh170

Reputation: 2990

There is no proper csv module for the question. Alternatively, you can probably use re module for regular expression match.

An example:

with open("file.csv") as f:
    data = f.readlines()
cities = [re.findall("(city.*)", line)[0] for line in data]
print cities

it should print all lines begin with keyword "city".

Upvotes: 0

Dan Lenski
Dan Lenski

Reputation: 79762

You need to come up with a way to detect the start and end of the relevant section of the file; the csv module does not contain any built-in mechanism for doing this by itself, because there is no general and unambiguous delimiter for the beginning and end of a particular section.

I have to question the wisdom of jamming multiple CSV files together like this. Is there a reason that you can't separate the sections into individual files?

Upvotes: 2

Related Questions