Reading data from a CSV file in Python

Although it's a pretty old question, just want to share my suggestion. Found it easier to read csv using pandas in a dataframe and access the data.

import pandas

df = pandas.read_csv('<path/to/your/csv/file>')

print(df)
#OUTPUT
#     col1     col2                       col3  col4
#0   name1   empId1   241682-27638-USD-CIGGNT      1
#1   name2   empId2  241682-27638-USD-OCGGINT      1
#2   name3   empId3    241942-37190-USD-GGDIV      2
#3   name4   empId4    241942-37190-USD-CHYOF      1
#4   name5   empId5     241942-37190-USD-EQPL      1
#5   name6   empId6      241942-37190-USD-INT      1
#6   name7   empId7    242066-15343-USD-CYJOF      3
#7   name8   empId8    242066-15343-USD-CYJOF      3
#8   name9   empId9    242066-15343-USD-CYJOF      3
#9  name10  empId10    241942-37190-USD-GGDIV      2

#you can access any column using

df['col2']
#OUTPUT
#0     empId1
#1     empId2
#2     empId3
#3     empId4
#4     empId5
#5     empId6
#6     empId7
#7     empId8
#8     empId9
#9    empId10
#Name: col2, dtype: object


#Or print a specific value using
df['col2'][0]

Update: I was mainly using Pandas in my project so found it easier to just use it to read the csv as well. There are other dedicated libraries available to read CSV (creating your own CSV reader should also be few lines of code).


Here is how I've got 2nd and 3rd columns:

import csv

path = 'c:\\temp\\'

file=open( path +"xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[1],line[2]
    print(t)

Here is the results:

('col2', 'col3')
('empId1', '241682-27638-USD-CIGGNT ')
('empId2', '241682-27638-USD-OCGGINT ')
('empId3', '241942-37190-USD-GGDIV ')
('empId4', '241942-37190-USD-CHYOF ')
('empId5', '241942-37190-USD-EQPL ')
('empId6', '241942-37190-USD-INT ')
('empId7', '242066-15343-USD-CYJOF ')
('empId8', '242066-15343-USD-CYJOF ')
('empId9', '242066-15343-USD-CYJOF ')
('empId10', '241942-37190-USD-GGDIV ')

Hope it clears the issue

import csv
file=open( "xyz.CSV", "r")
reader = csv.reader(file)
for line in reader:
    t=line[0]+","+line[1]
    print (t)

Your first line only has one column, so the process fails and doesn't continue. To solve, just skip first row

>>> with open( path, "r") as file:
...     reader = csv.reader(file)
...     for idx,line in enumerate(reader):
...         if idx>0:
...             t=line[1],line[2]
...             print t
... 
('empId1', '241682-27638-USD-CIGGNT ')
('empId2', '241682-27638-USD-OCGGINT ')
('empId3', '241942-37190-USD-GGDIV ')
('empId4', '241942-37190-USD-CHYOF ')
('empId5', '241942-37190-USD-EQPL ')
('empId6', '241942-37190-USD-INT ')
('empId7', '242066-15343-USD-CYJOF ')
('empId8', '242066-15343-USD-CYJOF ')
('empId9', '242066-15343-USD-CYJOF ')
('empId10', '241942-37190-USD-GGDIV ')

Tags:

Python

Csv