oznaprazzi oznaprazzi - 1 year ago 51
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:

Example file:





Answer Source

Suppose you want to add first column value of the csv file only to the list, then you can do this:

import csv
 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(",")

PS : I have assumed your input file like :


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.