3

I want to read only first column from csv file. I tried the below code but didn't got the result from available solution.

data = open('data.csv')
reader = csv.reader(data)
interestingrows = [i[1] for i in reader]'

The error I got is:

Traceback (most recent call last):
    File "G:/Setups/Python/pnn-3.py", line 12, in <module>
         interestingrows = [i[1] for i in reader]
    File "G:/Setups/Python/pnn-3.py", line 12, in <listcomp>
         interestingrows = [i[1] for i in reader]
IndexError: list index out of range
2
  • 1
    i[1] will give you the second column not the first. You should try i[0] Commented Apr 22, 2017 at 6:03
  • Possible duplicate of Reading each column from csv file Commented Apr 22, 2017 at 6:09

2 Answers 2

3

You can also use DictReader to access columns by their header

For example: If you had a file called "stackoverflow.csv" with the headers ("Oopsy", "Daisy", "Rough", and "Tumble") You could access the first column with this script:

import csv
with open(stackoverflow.csv) as csvFile:
#Works if the file is in the same folder, 
# Otherwise include the full path
    reader = csv.DictReader(csvFile)
    for row in reader:
        print(row["Oopsy"])
Sign up to request clarification or add additional context in comments.

4 Comments

Apologies, I'm new to all this. I've added code, how's it looking?
Try to be careful with the indentation as it won't work if it is not indented well. (I fix it with edit)
Useful tip: In question or answer (but not comment), select your code (in text or outside of it) and press Ctrl+K
I just had a try, that makes it so much easier to copy code from notepad onto the site! Thanks!
0

If you want the first item from an indexable iterable you should use 0 as the index. But in this case you can simply use zip() in order to get an iterator of columns and since the csv.reader returns an iterator you can use next() to get the first column.

with open('data.csv') as data:
    reader = csv.reader(data)
    first_column  = next(zip(*reader))

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.