Writing Python lists to columns in csv





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







27















I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:



with open('test.csv', 'wb') as f:
writer = csv.writer(f)
for val in test_list:
writer.writerow([val])


If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?










share|improve this question































    27















    I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:



    with open('test.csv', 'wb') as f:
    writer = csv.writer(f)
    for val in test_list:
    writer.writerow([val])


    If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?










    share|improve this question



























      27












      27








      27


      17






      I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:



      with open('test.csv', 'wb') as f:
      writer = csv.writer(f)
      for val in test_list:
      writer.writerow([val])


      If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?










      share|improve this question
















      I have 5 lists, all of the same length, and I'd like to write them to 5 columns in a CSV. So far, I can only write one to a column with this code:



      with open('test.csv', 'wb') as f:
      writer = csv.writer(f)
      for val in test_list:
      writer.writerow([val])


      If I add another for loop, it just writes that list to the same column. Anyone know a good way to get five separate columns?







      python list csv






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 17 '13 at 16:49









      Mike Mertsock

      9,43273266




      9,43273266










      asked Jul 17 '13 at 15:40









      Alex ChumbleyAlex Chumbley

      2843714




      2843714
























          6 Answers
          6






          active

          oldest

          votes


















          34














          change them to rows



          rows = zip(list1,list2,list3,list4,list5)


          then just



          import csv

          with open(newfilePath, "w") as f:
          writer = csv.writer(f)
          for row in rows:
          writer.writerow(row)





          share|improve this answer


























          • I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

            – Brans Ds
            Nov 30 '16 at 13:05



















          9














          The following code writes python lists into columns in csv



          import csv
          from itertools import zip_longest
          list1 = ['a', 'b', 'c', 'd', 'e']
          list2 = ['f', 'g', 'i', 'j']
          d = [list1, list2]
          export_data = zip_longest(*d, fillvalue = '')
          with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
          wr = csv.writer(myfile)
          wr.writerow(("List1", "List2"))
          wr.writerows(export_data)
          myfile.close()


          The output looks like this



          enter image description here






          share|improve this answer































            4














            You can use izip to combine your lists, and then iterate them



            for val in itertools.izip(l1,l2,l3,l4,l5):
            writer.writerow(val)





            share|improve this answer



















            • 5





              It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

              – Gareth Latty
              Jul 17 '13 at 15:47





















            0














            import csv
            dic = {firstcol,secondcol} #dictionary
            csv = open('result.csv', "w")
            for key in dic.keys():
            row ="n"+ str(key) + "," + str(dic[key])
            csv.write(row)





            share|improve this answer



















            • 2





              Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

              – Cindy Meister
              Oct 13 '18 at 21:17



















            0














            If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:



            import pandas as pd

            list1 = [1, 2, 3]
            list2 = [4, 5, 6]
            list3 = [7, 8, 9]

            df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

            df.to_csv('file.csv', index=False)

            print(df)

            Col0 Col1 Col2
            0 1 4 7
            1 2 5 8
            2 3 6 9





            share|improve this answer































              0














              I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:



              import csv
              list1 = ['a', 'b', 'c', 'd', 'e']
              list2 = ['f', 'g', 'i', 'j','k']
              with open('C:/test/numbers.csv', 'wb+') as myfile:
              wr = csv.writer(myfile)
              wr.writerow(("list1", "list2"))
              rcount = 0
              for row in list1:
              wr.writerow((list1[rcount], list2[rcount]))
              rcount = rcount + 1
              myfile.close()





              share|improve this answer


























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17704244%2fwriting-python-lists-to-columns-in-csv%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                6 Answers
                6






                active

                oldest

                votes








                6 Answers
                6






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                34














                change them to rows



                rows = zip(list1,list2,list3,list4,list5)


                then just



                import csv

                with open(newfilePath, "w") as f:
                writer = csv.writer(f)
                for row in rows:
                writer.writerow(row)





                share|improve this answer


























                • I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

                  – Brans Ds
                  Nov 30 '16 at 13:05
















                34














                change them to rows



                rows = zip(list1,list2,list3,list4,list5)


                then just



                import csv

                with open(newfilePath, "w") as f:
                writer = csv.writer(f)
                for row in rows:
                writer.writerow(row)





                share|improve this answer


























                • I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

                  – Brans Ds
                  Nov 30 '16 at 13:05














                34












                34








                34







                change them to rows



                rows = zip(list1,list2,list3,list4,list5)


                then just



                import csv

                with open(newfilePath, "w") as f:
                writer = csv.writer(f)
                for row in rows:
                writer.writerow(row)





                share|improve this answer















                change them to rows



                rows = zip(list1,list2,list3,list4,list5)


                then just



                import csv

                with open(newfilePath, "w") as f:
                writer = csv.writer(f)
                for row in rows:
                writer.writerow(row)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Sep 20 '17 at 3:00









                NRR

                500617




                500617










                answered Jul 17 '13 at 15:43









                Joran BeasleyJoran Beasley

                74.2k683122




                74.2k683122













                • I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

                  – Brans Ds
                  Nov 30 '16 at 13:05



















                • I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

                  – Brans Ds
                  Nov 30 '16 at 13:05

















                I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

                – Brans Ds
                Nov 30 '16 at 13:05





                I got something like: array([-23.], dtype=float32), array([-0.39999986], dtype=float32... how get pure values without types?

                – Brans Ds
                Nov 30 '16 at 13:05













                9














                The following code writes python lists into columns in csv



                import csv
                from itertools import zip_longest
                list1 = ['a', 'b', 'c', 'd', 'e']
                list2 = ['f', 'g', 'i', 'j']
                d = [list1, list2]
                export_data = zip_longest(*d, fillvalue = '')
                with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
                wr = csv.writer(myfile)
                wr.writerow(("List1", "List2"))
                wr.writerows(export_data)
                myfile.close()


                The output looks like this



                enter image description here






                share|improve this answer




























                  9














                  The following code writes python lists into columns in csv



                  import csv
                  from itertools import zip_longest
                  list1 = ['a', 'b', 'c', 'd', 'e']
                  list2 = ['f', 'g', 'i', 'j']
                  d = [list1, list2]
                  export_data = zip_longest(*d, fillvalue = '')
                  with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
                  wr = csv.writer(myfile)
                  wr.writerow(("List1", "List2"))
                  wr.writerows(export_data)
                  myfile.close()


                  The output looks like this



                  enter image description here






                  share|improve this answer


























                    9












                    9








                    9







                    The following code writes python lists into columns in csv



                    import csv
                    from itertools import zip_longest
                    list1 = ['a', 'b', 'c', 'd', 'e']
                    list2 = ['f', 'g', 'i', 'j']
                    d = [list1, list2]
                    export_data = zip_longest(*d, fillvalue = '')
                    with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
                    wr = csv.writer(myfile)
                    wr.writerow(("List1", "List2"))
                    wr.writerows(export_data)
                    myfile.close()


                    The output looks like this



                    enter image description here






                    share|improve this answer













                    The following code writes python lists into columns in csv



                    import csv
                    from itertools import zip_longest
                    list1 = ['a', 'b', 'c', 'd', 'e']
                    list2 = ['f', 'g', 'i', 'j']
                    d = [list1, list2]
                    export_data = zip_longest(*d, fillvalue = '')
                    with open('numbers.csv', 'w', encoding="ISO-8859-1", newline='') as myfile:
                    wr = csv.writer(myfile)
                    wr.writerow(("List1", "List2"))
                    wr.writerows(export_data)
                    myfile.close()


                    The output looks like this



                    enter image description here







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 17 '17 at 13:40









                    Ashok Kumar JayaramanAshok Kumar Jayaraman

                    1,10511219




                    1,10511219























                        4














                        You can use izip to combine your lists, and then iterate them



                        for val in itertools.izip(l1,l2,l3,l4,l5):
                        writer.writerow(val)





                        share|improve this answer



















                        • 5





                          It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

                          – Gareth Latty
                          Jul 17 '13 at 15:47


















                        4














                        You can use izip to combine your lists, and then iterate them



                        for val in itertools.izip(l1,l2,l3,l4,l5):
                        writer.writerow(val)





                        share|improve this answer



















                        • 5





                          It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

                          – Gareth Latty
                          Jul 17 '13 at 15:47
















                        4












                        4








                        4







                        You can use izip to combine your lists, and then iterate them



                        for val in itertools.izip(l1,l2,l3,l4,l5):
                        writer.writerow(val)





                        share|improve this answer













                        You can use izip to combine your lists, and then iterate them



                        for val in itertools.izip(l1,l2,l3,l4,l5):
                        writer.writerow(val)






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Jul 17 '13 at 15:45









                        jh314jh314

                        20.6k134870




                        20.6k134870








                        • 5





                          It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

                          – Gareth Latty
                          Jul 17 '13 at 15:47
















                        • 5





                          It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

                          – Gareth Latty
                          Jul 17 '13 at 15:47










                        5




                        5





                        It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

                        – Gareth Latty
                        Jul 17 '13 at 15:47







                        It's worth noting that itertools.izip() doesn't exist in Python 3.x, and the zip() built-in gives an iterator, so that is a drop-in replacement. Also note that if you have a list of lists, you can use the unpacking operator (zip(*lists)). This is better design than having variables l1, l2, etc...

                        – Gareth Latty
                        Jul 17 '13 at 15:47













                        0














                        import csv
                        dic = {firstcol,secondcol} #dictionary
                        csv = open('result.csv', "w")
                        for key in dic.keys():
                        row ="n"+ str(key) + "," + str(dic[key])
                        csv.write(row)





                        share|improve this answer



















                        • 2





                          Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

                          – Cindy Meister
                          Oct 13 '18 at 21:17
















                        0














                        import csv
                        dic = {firstcol,secondcol} #dictionary
                        csv = open('result.csv', "w")
                        for key in dic.keys():
                        row ="n"+ str(key) + "," + str(dic[key])
                        csv.write(row)





                        share|improve this answer



















                        • 2





                          Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

                          – Cindy Meister
                          Oct 13 '18 at 21:17














                        0












                        0








                        0







                        import csv
                        dic = {firstcol,secondcol} #dictionary
                        csv = open('result.csv', "w")
                        for key in dic.keys():
                        row ="n"+ str(key) + "," + str(dic[key])
                        csv.write(row)





                        share|improve this answer













                        import csv
                        dic = {firstcol,secondcol} #dictionary
                        csv = open('result.csv', "w")
                        for key in dic.keys():
                        row ="n"+ str(key) + "," + str(dic[key])
                        csv.write(row)






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Oct 13 '18 at 18:45









                        Shb8086Shb8086

                        111




                        111








                        • 2





                          Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

                          – Cindy Meister
                          Oct 13 '18 at 21:17














                        • 2





                          Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

                          – Cindy Meister
                          Oct 13 '18 at 21:17








                        2




                        2





                        Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

                        – Cindy Meister
                        Oct 13 '18 at 21:17





                        Your contribution would be more meaningful if you would include some explanation about why this approach should work and be an improvement over what has already been proposed and accepted as the answer.

                        – Cindy Meister
                        Oct 13 '18 at 21:17











                        0














                        If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:



                        import pandas as pd

                        list1 = [1, 2, 3]
                        list2 = [4, 5, 6]
                        list3 = [7, 8, 9]

                        df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

                        df.to_csv('file.csv', index=False)

                        print(df)

                        Col0 Col1 Col2
                        0 1 4 7
                        1 2 5 8
                        2 3 6 9





                        share|improve this answer




























                          0














                          If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:



                          import pandas as pd

                          list1 = [1, 2, 3]
                          list2 = [4, 5, 6]
                          list3 = [7, 8, 9]

                          df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

                          df.to_csv('file.csv', index=False)

                          print(df)

                          Col0 Col1 Col2
                          0 1 4 7
                          1 2 5 8
                          2 3 6 9





                          share|improve this answer


























                            0












                            0








                            0







                            If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:



                            import pandas as pd

                            list1 = [1, 2, 3]
                            list2 = [4, 5, 6]
                            list3 = [7, 8, 9]

                            df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

                            df.to_csv('file.csv', index=False)

                            print(df)

                            Col0 Col1 Col2
                            0 1 4 7
                            1 2 5 8
                            2 3 6 9





                            share|improve this answer













                            If you are happy to use a 3rd party library, you can do this with Pandas. The benefits include seamless access to specialized methods and row / column labeling:



                            import pandas as pd

                            list1 = [1, 2, 3]
                            list2 = [4, 5, 6]
                            list3 = [7, 8, 9]

                            df = pd.DataFrame(list(zip(*[list1, list2, list3]))).add_prefix('Col')

                            df.to_csv('file.csv', index=False)

                            print(df)

                            Col0 Col1 Col2
                            0 1 4 7
                            1 2 5 8
                            2 3 6 9






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 22 '18 at 12:20









                            jppjpp

                            103k2166116




                            103k2166116























                                0














                                I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:



                                import csv
                                list1 = ['a', 'b', 'c', 'd', 'e']
                                list2 = ['f', 'g', 'i', 'j','k']
                                with open('C:/test/numbers.csv', 'wb+') as myfile:
                                wr = csv.writer(myfile)
                                wr.writerow(("list1", "list2"))
                                rcount = 0
                                for row in list1:
                                wr.writerow((list1[rcount], list2[rcount]))
                                rcount = rcount + 1
                                myfile.close()





                                share|improve this answer






























                                  0














                                  I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:



                                  import csv
                                  list1 = ['a', 'b', 'c', 'd', 'e']
                                  list2 = ['f', 'g', 'i', 'j','k']
                                  with open('C:/test/numbers.csv', 'wb+') as myfile:
                                  wr = csv.writer(myfile)
                                  wr.writerow(("list1", "list2"))
                                  rcount = 0
                                  for row in list1:
                                  wr.writerow((list1[rcount], list2[rcount]))
                                  rcount = rcount + 1
                                  myfile.close()





                                  share|improve this answer




























                                    0












                                    0








                                    0







                                    I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:



                                    import csv
                                    list1 = ['a', 'b', 'c', 'd', 'e']
                                    list2 = ['f', 'g', 'i', 'j','k']
                                    with open('C:/test/numbers.csv', 'wb+') as myfile:
                                    wr = csv.writer(myfile)
                                    wr.writerow(("list1", "list2"))
                                    rcount = 0
                                    for row in list1:
                                    wr.writerow((list1[rcount], list2[rcount]))
                                    rcount = rcount + 1
                                    myfile.close()





                                    share|improve this answer















                                    I didn't want to import anything other than csv, and all my lists have the same number of items. The top answer here seems to make the lists into one row each, instead of one column each. Thus I took the answers here and came up with this:



                                    import csv
                                    list1 = ['a', 'b', 'c', 'd', 'e']
                                    list2 = ['f', 'g', 'i', 'j','k']
                                    with open('C:/test/numbers.csv', 'wb+') as myfile:
                                    wr = csv.writer(myfile)
                                    wr.writerow(("list1", "list2"))
                                    rcount = 0
                                    for row in list1:
                                    wr.writerow((list1[rcount], list2[rcount]))
                                    rcount = rcount + 1
                                    myfile.close()






                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Feb 1 at 16:46

























                                    answered Feb 1 at 16:40









                                    BartatsBartats

                                    11




                                    11






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f17704244%2fwriting-python-lists-to-columns-in-csv%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Biblatex bibliography style without URLs when DOI exists (in Overleaf with Zotero bibliography)

                                        ComboBox Display Member on multiple fields

                                        Is it possible to collect Nectar points via Trainline?