DyTech
DyTech

Reputation: 159

Extracting data using fieldnames

I have parsed and extracted lines and field names from a CSV data file using:

reader = csv.DictReader(open('Sourcefile.txt','rt'), delimiter = '\t')
fn = reader.fieldnames

How do I access the parsed data in any line using the fieldname? For example fieldnames could be AA, BB, CC, DD. How do obtain the value for DD in line 5, or AA in line 3?

Upvotes: 1

Views: 81

Answers (2)

qRTPCR
qRTPCR

Reputation: 1736

An easy way is to store all of the data in your file into a container. An alternative to the other answer is to use a pandas dataframe:

>>import pandas as pd
>>from io import StringIO  # just to make a fake in memory file
>>s = StringIO('AA\tBB\tCC\tDD\n1\t2\t3\t4\n11\t12\t13\t14\n') # fake data
>>data = pd.read_table(s)
>>data.loc[0,'AA']  # access row 0 (the first row) and column AA
1

Edit: This does use a different package not included with the standard library, but I often find it easier to use pandas than csv when I am constantly reading and manipulating csv files.

Upvotes: 0

Mike Müller
Mike Müller

Reputation: 85442

As long as the file is not too big just convert the reader into a list:

data = list(reader)

Now access the column AA in row 1:

data[0]['AA']

or column for field name 3 in row 3:

data[2][fn[2]]

Upvotes: 2

Related Questions