I am reading data from a CSV file (xyz.CSV) which contains below data:
col1,col2,col3,col4 name1,empId1,241682-27638-USD-CIGGNT ,1 name2,empId2,241682-27638-USD-OCGGINT ,1 name3,empId3,241942-37190-USD-GGDIV ,2 name4,empId4,241942-37190-USD-CHYOF ,1 name5,empId5,241942-37190-USD-EQPL ,1 name6,empId6,241942-37190-USD-INT ,1 name7,empId7,242066-15343-USD-CYJOF ,3 name8,empId8,242066-15343-USD-CYJOF ,3 name9,empId9,242066-15343-USD-CYJOF ,3 name10,empId10,241942-37190-USD-GGDIV ,2
When I am iterating it with a loop I am able to print the data row wise and and only column1 data by the below code.
file=open( path +"xyz.CSV", "r") reader = csv.reader(file) for line in reader: t=line[0] print t
By the above code I can only get the first column.
If I try to print line[1] or line[2] it gives me the below error.
file=open( path +"xyz.CSV", "r") reader = csv.reader(file) for line in reader: t=line[1],[2] print t t=line[1],line[2] IndexError: list index out of range
Please suggest for printing the data of column2 or column3.
Parsing CSV files in Python is quite easy. Python has an inbuilt CSV library which provides the functionality of both readings and writing the data from and to CSV files.
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 ')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With