Python 将列表列表写入CSV,但仅获取密钥

Python 将列表列表写入CSV,但仅获取密钥,python,csv,Python,Csv,我有大约60个CSV,每个CSV有4个公共值,我需要提取并转换成一个CSV。我在这里删掉了很多信息,但确认了“output\u contents”包含了所有正确的信息,但在我调用“create\u csv”时没有写入这些信息 def create_csv(list_of_lists): ''' Writes the list of lists to a actual CSV file. PARAMS: list_of_lists - A lis

我有大约60个CSV,每个CSV有4个公共值,我需要提取并转换成一个CSV。我在这里删掉了很多信息,但确认了“output\u contents”包含了所有正确的信息,但在我调用“create\u 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)
我已经确认输出内容包含了输入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)

<> >代码> WordRoS< /Cord>方法期望一个迭代列表,但您提供了一个字符串列表(这使得函数迭代字符串,并将每个字符视为一个值)。所以你应该用

output_contents = ((key, value) for key, value in content.items() if key in wanted_columns)
create_csv
功能中

writer.writerows(list_of_lists)

希望有帮助

也许你可以把一个工作代码,我们可以复制,粘贴和发现问题:)谢谢你的回答。我不得不修改我的数据格式,你的回答让我知道应该如何格式化。