Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading columns as lists

Tags:

python

csv

I have data in a txt file in the form. Tab-delimited data

here
     a b c
     e f g
tere
     x y z
     w t y

I need to read the columns into lists. like

col1 = ['here', '', '', tere, '', '']
col2= ['', 'a', 'e', '', 'x'.'w']

and so on.

I have used

import re

infile = open('text.txt', 'r')
i=0
a0='';a1='';a2='';a3='';a4='';a5='';a6='';a7='';
for line in infile:
    [a1[i],a2[i],a3[i],a4[i],a5[i],a6[i],a7[i],a8[i]] = line.split('\t')
    i+=1

It says 'str' object does not support item assignment.

Any tips?

like image 506
Zero Avatar asked Feb 18 '23 01:02

Zero


2 Answers

If you want all the data assigned to variables per column, start with a list:

per_row = []
for line in infile:
    per_row.append(line.strip().split('\t'))

And only then turn that into a list of columns:

per_column = zip(*per_row)

This is now a list of lists; per_column[0] is the first column of data.

You really want to use the csv module instead to read tabular data though.

Your code, unfortunately, is not nearly close enough to working Python. You assigned several variables the empty string, then tried to use them as lists.

like image 76
Martijn Pieters Avatar answered Feb 19 '23 21:02

Martijn Pieters


Correction to @Martijn Pieters answer

It should have been like this

per_row = []
for line in infile:
    per_row.append(line.split('\t'))

And only then turn that into a list of columns:

per_column = zip(*per_row)

This is now a list of lists; per_column[0] is the first column of data.

This gives the result i want. strip() removes blank cells also.

like image 43
Zero Avatar answered Feb 19 '23 19:02

Zero