2017-04-25 118 views
0

我有一個tab分隔文件,包含7列。我想把每一列放在python的單獨列表中。之後,我會有一個包含7個Python列表的列表。 我試過,但它把每行一個單獨的列表:將文本文件轉換爲python列表中的列表

infile = open('text.txt', 'r') 
s = [] 
for line in infile: 
    s.append(line.strip().split('\t')) 

你知道我怎麼能解決這個問題?

+2

如果是正確的TSV,使用'csv'模塊:HTTPS ://docs.python.org/3/library/csv.html –

回答

1

嘗試:

infile = open('text.txt', 'r') 
s = [[], [], [], [], [], [], []] 
for line in infile: 
    t = line.strip().split('\t') 
    for i, p in enumerate(t): 
     s[i].append(p) 

print(s) 

考慮文件包含:

1 2 3 4 5 6 7 
8 9 10 11 12 13 14 

輸出:

[['1', '8'], ['2', '9'], ['3', '10'], ['4', '11'], ['5', '12'], ['6 ', '13'], ['7', '14']] 
0
infile = open('text.txt', 'r') 
s = [] 
for line in infile: 
    count=0 
    for item in line.split("\t"): 
     s[count].append(item) 
     count=count+1 
+0

你也可以添加一些ex對你的代碼進行規劃。 – xhg

相關問題