manipulation of csv format in python files

前端 未结 1 1558
星月不相逢
星月不相逢 2021-01-28 01:21

I have combined two lists using zip syntax. When I saved it in csv format, whole data are stayed in one cell of excell. what\'s that i want is: each element of zipped file shoul

相关标签:
1条回答
  • 2021-01-28 01:32

    You've got two ways of doing this, assuming that you're using the csv module. You can either use writer.writerows:

    list_of_first_column = ["banana", "cat", "brown"]
    list_of_second_column = ["fruit", "animal", "color"]
    
    graph_zip_file = zip(list_of_first_column, list_of_second_column)
    with open('graph.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerows(graph_zip_file)
    

    Or, you can use writer.writerow and a for-loop:

    list_of_first_column = ["banana", "cat", "brown"]
    list_of_second_column = ["fruit", "animal", "color"]
    
    graph_zip_file = zip(list_of_first_column, list_of_second_column)
    with open('graph.csv', 'w') as csv_file:
        writer = csv.writer(csv_file)
        for row in graph_zip_file
            writer.writerow(row)
    

    They both should return the same thing, which is what you've indicated as your desired output.

    I hope this proves useful.

    0 讨论(0)
提交回复
热议问题