Zer*_*ero 4 python tab-delimited delimited-text tab-delimited-text
我在表单中的txt文件中有数据.制表符分隔的数据
here
a b c
e f g
tere
x y z
w t y
Run Code Online (Sandbox Code Playgroud)
我需要将列读入列表.喜欢
col1 = ['here', '', '', tere, '', '']
col2= ['', 'a', 'e', '', 'x'.'w']
Run Code Online (Sandbox Code Playgroud)
等等.
我用过
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
Run Code Online (Sandbox Code Playgroud)
它说'str'对象不支持项目分配.
有小费吗?
如果您希望每列分配给变量的所有数据,请从列表开始:
per_row = []
for line in infile:
per_row.append(line.strip().split('\t'))
Run Code Online (Sandbox Code Playgroud)
然后才将其转换为列列表:
per_column = zip(*per_row)
Run Code Online (Sandbox Code Playgroud)
这是一个列表清单; per_column[0]是第一列数据.
您确实希望使用该csv模块来读取表格数据.
遗憾的是,您的代码与Python的工作距离不够近.您为空字符串分配了几个变量,然后尝试将它们用作列表.