2015-10-05 81 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