0

I have a csv file in the following format:

    x1   x2    x3
    1     1     1
    2     2     2
    3     3     3
    4     4     4
    5     5     5

Can someone please let me know how can I access just the first column in this file?

1
  • You say that's a comma separated file, but I don't see any comments in the data. Commented May 27, 2013 at 20:44

2 Answers 2

3

To access columns by name (I'm not sure if your delimiter is actually ' ' or not but you can change that to ','):

import csv
with open('data.csv', 'rb') as f:
    r = csv.DictReader(f, delimiter=' ', skipinitialspace=True)
    print [row['x1'] for row in r]

['1', '2', '3', '4', '5']
Sign up to request clarification or add additional context in comments.

1 Comment

@user2386695: That means you haven't specified the correct delimiter. Which character separates one value from the next? Is it a tab perhaps?
1

You can read it without using the csv module:

with open('data.csv') as fobj:
    next(fobj)
    x1 = [line.split(None, 1)[0] for line in fobj]
 print x1 

result:

['1', '2', '3', '4', '5']

The with opens the file with the gurantee that it will be close as soon as you dedent. In our case at print x1. In Python an opened file, here fobj, is an iterator. We consume the first line with next and extract the first entry in each line using a list comprehension. The .split(None, 1) splits at all kinds of whitespaces such space, tab or newline and limits the split to the first column. This might be more performant for large files but surely does not matter here. A plain .split() would also work. The [0] fetches the first element of the list.

Variation with converting the numbers to ints:

with open('data.csv') as fobj:
    next(fobj)
    x1 = [int(line.split(None, 1)[0]) for line in fobj]
 print x1 

result:

[1, 2, 3, 4, 5]

Conclusion: The csv module is great but Python is so powerful that you can do it even without it for a lot of cases. If the file content is somewhat irregular and the csv chokes on it, it is always good to know how to do it "by hand".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.