Skip to content Skip to sidebar Skip to footer

Python - Reading Specific Column From Csv File

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) interest

Solution 1:

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
withopen(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"])

Solution 2:

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.

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

Post a Comment for "Python - Reading Specific Column From Csv File"