2015-10-05 39 views
1

我有大約60個CSV,每個都有4個公共值,我需要將其提取並轉換爲一個CSV。我在這裏刪除了很多信息,但確認'output_contents'具有所有正確的信息,但是當我調用'create_csv'時,它不會被寫入。將列表的列表寫入CSV,但只能獲取密鑰

  
def create_csv(list_of_lists): 
    ''' 
    Writes the list of lists to a actual CSV file. 

    PARAMS: 
    list_of_lists - A list of keys, and each key is a list of values. 

    RETURNS: None. 

    OUTPUTS: A CSV file named "output.csv". 
    ''' 
    print "Attempting to write CSV." 
    with open("output.csv", "wb") as f: 
     writer = csv.writer(f) 
     writer.writerows(list_of_lists.keys()) 
     print "Write successful." 

fileList = get_all_files(csv_directory) 
get_csv_contents(fileList) 

# Copy over the columns from the contents dictionary. 
wanted_columns = ["key1", "key2", "key2", "key4",] 

# Creates a key: value pair for every key and value in content as long as the key is a wanted column. 
output_contents = {key: value for key, value in content.items() if key in wanted_columns} 

create_csv(output_contents) 

我已確認output_contents包含來自應該輸入CSV的所有信息。

當我運行此,我output.csv樣子:


k,e,y,1 
k,e,y,2 
k,e,y,3 
k,e,y,4 

我知道我在什麼地方做一些小的,愚蠢的錯誤,但認爲我的大腦是油炸和想不通的地方呃是。

編輯:

這是可運行的代碼。

import csv 

def create_csv(list_of_lists): 
    ''' 
    Writes the list of lists to a actual CSV file. 

    PARAMS: 
    list_of_lists - A list of keys, and each key is a list of values. 

    RETURNS: None. 

    OUTPUTS: A CSV file named "output.csv". 
    ''' 
    print "Attempting to write CSV." 
    with open("output.csv", "wb") as f: 
     writer = csv.writer(f) 
     writer.writerows(list_of_lists.keys()) 
     print "Write successful." 



output_contents = { 
     'key1': ["k1v1","k1v2","k1v3"], 
     'key2': ["k2v1","k2v2","k2v3"], 
     'key3': ["k3v1","k3v2","k3v3"], 
     'key4': ["k4v1","k4v2","k4v3"],} 

create_csv(output_contents) 
+0

也許你可以把我們可以複製,粘貼並找到問題的工作代碼:) – cdonts

回答

1

writerows方法需要iterables的名單,但你要提供一個字符串列表(這會導致遍歷字符串,並考慮每個字符作爲值的函數)。所以,你應該使用,而不是...

output_contents = ((key, value) for key, value in content.items() if key in wanted_columns) 

而在create_csv功能...

writer.writerows(list_of_lists) 

希望它能幫助!

+0

感謝您的回答。我不得不修改我的數據格式,而你的答案幫助我知道應該如何格式化。 – JRodge01

+0

@JohnRodgers不客氣! – cdonts