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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With