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


i want create list specific column of file, example csv file. how append each value in column without knowing index?

i created loop find index of specific column want append list, not seem correct. need somehow make use of ".split()" method. appreciated :)

filename = open(file_name) row = filename.readline() index1 = 0 index2 = 0 list1 = [] list2 = []  i, value in enumerate(row.split(",")):    if value "value1":       index1 =    elif str(value) "value2":        index2 =  rows = filename.readlines() 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 

suppose want add first column value of csv file list, can this:

import csv lst=[]  open('fl.csv', 'rb') csvfile: ...     reader = csv.reader(csvfile) ...     row in reader: ...        lst.add(row[1]); 

since have use split, :

ans = [] file = open("sample.csv") text = file.read() lst = text.split("\n") l in lst:     p = l.split(",")     ans.add(p[1]) 

ps : have assumed input file :

hello,hi,bye wow,nice,good .... 

for code work, instead of comparing strings use ==.

if value == "value1" 

is return true if 2 variables point same object, == if objects referred variables equal.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -