2015-12-21 49 views
0

我一直在編寫一個從3個外部源獲取數據的腳本。結合來自不同來源的變量並將它們寫入CSV(Python)

def fetch1(): 
    return array 
def fetch2(): 
    return array2 
def fetch3(): 
    return array3 

列表中的所有元素都相互關聯。即數組[0],數組2 [0],數組3 [0]應該放在一起csv。

array2的一些元素可能是空白的。

現在我想把它們全部寫入一個csv文件。數組的例子:

array = ["dog", "cat", "horse", "lion"] 
array2 = ["500USD", "300USD", "900USD", ""] 
array3 = ["Buy", "Sell", "Buy", "Buy"] 

以及如何將它們寫在我每次啓動這個腳本的方式,數據應該先前輸入的,而不是做一個新的文件,數據後輸入。

我迄今爲止嘗試:

我創建因爲這樣ARRAY2元素可以是空的事實陣列和數組2的字典。然後我寫了下面的函數。

def write(): 
    writer = csv.writer(open('dict.csv', 'wb')) 
    for key, value in arrayNarray2.items(): 
     writer.writerow([key.encode("UTF-8"), value.encode("UTF-8")]) 
+0

更新了我的問題。 @BenC – Sanidhay

回答

2

這是你想要的輸出格式嗎?

"dog", "500USD", "Buy" 
"cat", "300USD", "Sell" 
... 

如果是這樣,那麼你可以使用zip所有在你的列表,第一個項目的結合,那麼所有的第二個項目,等:

from itertools import izip_longest 

with open('dict.csv', 'ab') as out: 
    writer = csv.writer(out) 
    for row in izip_longest(array, array2, array3): 
     writer.writerow([x.encode("utf-8") for x in row]) 

我用izip_longest因爲你說的列表的長度可能不同,因此缺少任何內容將填寫None

+0

謝謝,但有沒有一種方法可以在前兩個數組中使用字典?並保持array3不變。因爲序列號在所有這三件事情中都是通用的。 – Sanidhay

+0

@Sanidhay你的字典是什麼樣的?我不完全確定你想要什麼輸入和輸出,或者你如何組合前兩個陣列。 – BenC

+0

根據你的回答,我已經準備好了我的代碼。我得到了我想要的結果,謝謝@BenC – Sanidhay

1

你必須以追加模式而不是寫模式打開你的文件。

錯誤代碼:

writer = csv.writer(open('dict.csv', 'wb')) 

修正版本:(附加字符可以遵循這些序列)

writer = csv.writer(open('dict.csv', 'ab')) 

參數模式指向與以下 序列之一開始的字符串:

``r'' Open text file for reading. The stream is positioned at the 
     beginning of the file. 

``r+'' Open for reading and writing. The stream is positioned at the 
     beginning of the file. 

``w'' Truncate file to zero length or create text file for writing. 
     The stream is positioned at the beginning of the file. 

``w+'' Open for reading and writing. The file is created if it does not 
     exist, otherwise it is truncated. The stream is positioned at 
     the beginning of the file. 

``a'' Open for writing. The file is created if it does not exist. The 
     stream is positioned at the end of the file. Subsequent writes 
     to the file will always end up at the then current end of file, 
     irrespective of any intervening fseek(3) or similar. 

``a+'' Open for reading and writing. The file is created if it does not 
     exist. The stream is positioned at the end of the file. Subse- 
     quent writes to the file will always end up at the then current 
     end of file, irrespective of any intervening fseek(3) or similar. 

將上述內容複製到f rom python open built-in function: difference between modes a, a+, w, w+, and r+?

+0

謝謝,那麼在追加時選擇特定的行號呢? – Sanidhay

+0

@Sanidhay - 它不是直接在文件中間追加數據。最後可以追加。 –

相關問題