Get row index instead of columns in csv file

First of all, let me say that I'm extremely new to Python or some kind of programming program. In addition, I was not sure what to put as the name, sorry. So, I opened this csv file, then split and separated the commas, and then to check, I printed it out and it gave me this (only some example numbers):

['1','2','3','4'] ['5','6','7','8'] ['9','10','11','12'] 

I was wondering if there is a way to index rows instead of columns, for example if I try to print my_list [0] this will give me 1 5 9

instead of ['1', '2', '3', '4']. My actual problem is that I need to convert the csv data into a series of tuples with elements that are facing integers, and be able to select any of the lines for further processing.

I am not familiar with the many modules that I have seen on this site. I liked the really basic encoding if possible (although sometimes it is inefficient)

Thanks!

+4
source share
2 answers

This answer follows your comments for the answer provided by stranac and tries to create my_list as you wish

 my_list = [] with open('Test.csv', 'r') as csvfile: for lines in csvfile: temp_lines = lines.strip().split(',') my_list.append(temp_lines) print(my_list) 

However, I would suggest that you use the csv module already available in python. You can see the basic example here

You can do something like this:

 import csv my_list = [] with open('Test.csv') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: my_list.append(row) print(my_list) 
+1
source

You can use a fairly simple list comprehension to convert your list to the desired format (after getting the list from csv), using zip(*my_list) to transpose it:

 >>> my_list = [['1','2','3','4'], ... ['5','6','7','8'], ... ['9','10','11','12']] >>> [[int(x) for x in row] for row in zip(*my_list)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] 
+2
source

Source: https://habr.com/ru/post/1441186/


All Articles