Reputation: 173
I have a csv file with two columns. I am trying to read that second column from that csv file to a list in python . I referred to some of the ways in stackoverflow. I tried them, but I am getting an error.
noise_amp=[] #an empty list to store the second column
with open('null_ch1_waveform_10mV.csv', 'rb') as rf:
reader = csv.reader(rf, delimiter=';')
for row in reader:
noise_amp.extend([row[1]])
I am getting this error:
Traceback (most recent call last):
File "J:/Ramu_Scripts/noise_script/source_code.py", line 58, in <module>
noise_amp.extend([row[1]])
IndexError: list index out of range
My csv file is like
1,2
2,3
3,4
4,5
Upvotes: 0
Views: 21229
Reputation: 56
The following code works for me. I think its the issue with your delimiter. If yours is a normal csv file, then you need not use the delimiter argument.
import csv
noise_amp=[]
with open('glass.csv', 'r') as rf:
reader = csv.reader(rf)
for i in reader:
noise_amp.extend([i[1]])
Upvotes: 2
Reputation: 7504
Try this :
import csv
noise_amp=[] #an empty list to store the second column
with open('demo.csv', 'r') as rf:
reader = csv.reader(rf, delimiter=',')
for row in reader:
noise_amp.append(row[1])
Use r
or rb
as open mode and delimiter be ,
Upvotes: 6
Reputation: 4004
The easiest solution i can think of, without using the builtin csv module* is the following:
with open(csv_file, 'r') as f:
for row in f:
second_data = row.split(',')[1]
Than you can do anything you want with it
* Not using the csv module isn't really pythonic, Take a look at it if you want clean code
Upvotes: 2