2014-01-08 52 views
0

我有以下文件,salida.txt其在本例中的列數不同,只是2閱讀文件,並創建陣列,每列的話

cil HUF, M1 NSS, 
442, 1123, 
20140130, 2014012, 
20140131, 2014014, 

我想讀的文件和將每列添加到一個新的數組中。我wan't有這樣的:

['cli HUF', '442', '20140130', '20140131'] 
[' M1 NSS', '1123', '2014012', '2014014'] 

我試過到目前爲止:

file = open('salida.txt', 'r') 
for line in file: 
    // add them to the arrays 

我有問題要處理(陣列的數量也並不總是2,取決於文件的列數)並從行中取出每個單詞以添加到適當的數組中。如果我把它放在循環內print line[0]它打印整個行,我想逐字處理它。

+0

你是什麼意思它並不總是2 ?它可以更多或更少? – aIKid

+0

它是數組的數量(取決於列),而不是它們的大小,它總是相同的,4.我編輯了消息。 –

回答

1
arrays = [] 
with open('salida.txt', 'r') as wordfile: 
    for line in wordfile: 
     # Split the line on commas. 
     words = line.split(',') 
     for count, word in enumerate(words): 
      # Remove any whitespace. 
      word = word.strip() 
      # That might leave a blank string, e.g. at the end. 
      if word: 
       # Do we need to add another array to our list of arrays? 
       if count == len(arrays): 
        arrays.append([]) 
       arrays[count].append(word) 
print arrays 
1

地帶的最後一個逗號,然後一分爲中心逗號行:

list1, list2 = [], [] 
file = open('salida.txt', 'r') 
for line in file: 
    w1, w2 = line.strip(',').split(', ') 
    list1.append(w1) 
    list2.append(w2) 
+0

謝謝,但在這裏你創建了2個數組作爲例子,但正如我在文中所說的,數組的數量是可變的,這取決於行數。 –

+1

啊,我明白了。有不同數量的列嗎? – aIKid

+0

是的,它取決於'salida.txt'文件的列數。如果有6列,則會有6個數組等,這2個只是一個例子來顯示我的問題。 –

1

你去那裏:

file = open('salida.txt', 'r') 
lines = file.readlines() 
file.close() 
arrays = [] 
words = lines[0].split(",") 
for i in range(0,len(words)): 
    arrays.append([words[i]]) 
for i in range(1,len(lines)): 
    words = lines[i].split(",") 
    for j in range(0,len(words)): 
     arrays[j].append(words[j]) 
+0

謝謝,但在這裏你創建了2個數組作爲例子,但正如我在文本中所說的,數組的數量是可變的,這取決於行數。 –

+0

對不起,沒有仔細閱讀;回答修改... –

1
import csv 

with open('salida.txt') as f: 
    whatYouWant = zip(*list(csv.reader(f)))[:-1]