I want to create a list from a specific column of a file, for example a csv file. How would I append each value in a column without knowing the index?
I created a for loop to find the index of the specific column I want to append to the list, but it does not seem to be correct. I need to somehow make use of the ".split()" method. Much help appreciated :)
filename = open(file_name)
row = filename.readline()
index1 = 0
index2 = 0
list1 = 
list2 = 
for i, value in enumerate(row.split(",")):
if value is "value1":
index1 = i
elif str(value) is "value2":
index2 = i
rows = filename.readlines()
for value in rows:
Suppose you want to add first column value of the csv file only to the list, then you can do this:
import csv lst= with open('fl.csv', 'rb') as csvfile: ... reader = csv.reader(csvfile) ... for row in reader: ... lst.add(row);
Since you have to use split, do this :
ans =  file = open("sample.csv") text = file.read() lst = text.split("\n") for l in lst: p = l.split(",") ans.add(p)
PS : I have assumed your input file like :
hello,hi,bye wow,nice,good ....
For your code to work, instead of comparing strings with is use ==.
if value == "value1"
is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.