oznaprazzi oznaprazzi - 6 months ago 6
Python Question

How do I create a list from a column of a file?

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:
list1.append(int(value.split(",")[index1]))
list2.append(int(value.split(",")[index2]))


Example file:

a,b,value1,value2

1,2,3,4

4,5,6,7

1,2,3,4

Answer

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[1]);

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[1])

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.

Comments