{"id":2235,"date":"2018-07-28T18:54:01","date_gmt":"2018-07-28T23:54:01","guid":{"rendered":"http:\/\/bluegalaxy.info\/codewalk\/?p=2235"},"modified":"2018-07-28T18:54:37","modified_gmt":"2018-07-28T23:54:37","slug":"python-write-csv-file","status":"publish","type":"post","link":"https:\/\/bluegalaxy.info\/codewalk\/2018\/07\/28\/python-write-csv-file\/","title":{"rendered":"Python: How to write to a .csv file"},"content":{"rendered":"<p>Just like reading from .csv files, writing to .csv files also requires importing the csv module.<\/p>\n<blockquote class=\"wp-embedded-content\" data-secret=\"BPtctHLFbZ\"><p><a href=\"http:\/\/bluegalaxy.info\/codewalk\/2018\/07\/28\/python-open-read-csv-documents\/\">Python: How to open and read .csv documents<\/a><\/p><\/blockquote>\n<p><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" src=\"http:\/\/bluegalaxy.info\/codewalk\/2018\/07\/28\/python-open-read-csv-documents\/embed\/#?secret=BPtctHLFbZ\" data-secret=\"BPtctHLFbZ\" width=\"600\" height=\"338\" title=\"&#8220;Python: How to open and read .csv documents&#8221; &#8212; Chris Nielsen Code Walk\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe><\/p>\n<p>First define the path and name of your output file, then carefully build your output such that every line you want to write in the .csv file is a list with the same number of elements. For example, here is what the code should look like so far:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">import csv\r\n\r\nwritepath = r'C:\\Users\\Chris\\Desktop\\python-blog\\write_example.csv'\r\n\r\nrow1 = ['Sub region', 'Old QTR', 'New QTR', 'Difference', '% Change', 'Comments']\r\nrow2 = ['Traffic Direction Record', '6', '6', '0', 'n\/a', 'n\/a']\r\nrow3 = ['Traffic Event Record', '2523', '2523', '0', 'n\/a', 'n\/a']\r\nrow4 = ['Traffic Location Record', '34140', '38576', '4436', '12%', 'Increase']\r\nrow5 = ['Totals', '36669', '41105', '4436', '12%', 'Increase']<\/pre>\n<p>For the rest of this example I will use a try\/except block, a &#8216;with open() as var&#8217; construct, &#8216;wb&#8217; as the second argument to the open() function, a csv.writer object with a comma as the delimiter:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\">try:\r\n    with open(writepath, 'wb') as outfile:\r\n        writer = csv.writer(outfile, delimiter = \",\")\r\n\r\n        # Note: You could just as easily use a control loop here to iterate\r\n        # through all the rows you want to write.. The below example shows how to write\r\n        # each row individually, without using iteration\r\n\r\n        writer.writerow(row1)\r\n        writer.writerow(row2)\r\n        writer.writerow(row3)\r\n        writer.writerow(row4)\r\n        writer.writerow(row5)\r\n\r\nexcept:\r\n    print \"Write Error: Permission denied. Can't open\", writepath\r\n\r\nprint \"Success! The file has been written here:\", writepath<\/pre>\n<p>Running this script, I got this message on my screen:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"no-highlight\">Success! The file has been written here: C:\\Users\\Chris\\Desktop\\python-blog\\write_example.csv<\/code><\/p>\n<p>Then when I opened up the write_example.csv file in Excel, I see:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2239\" src=\"http:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/07\/write-example.png\" alt=\"\" width=\"534\" height=\"138\" srcset=\"https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/07\/write-example.png 534w, https:\/\/bluegalaxy.info\/codewalk\/wp-content\/uploads\/2018\/07\/write-example-300x78.png 300w\" sizes=\"auto, (max-width: 534px) 100vw, 534px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>For more information about csv.writer(), see:<br \/>\n<a href=\"https:\/\/docs.python.org\/2\/library\/csv.html\">https:\/\/docs.python.org\/2\/library\/csv.html<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Just like reading from .csv files, writing to .csv files also requires importing the csv module. Python: How to open and read .csv documents First define the path and name of your output file, then carefully build your output such that every line you want to write in the .csv file is a list with &hellip; <a href=\"https:\/\/bluegalaxy.info\/codewalk\/2018\/07\/28\/python-write-csv-file\/\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Python: How to write to a .csv file<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[8,161,4,162],"class_list":["post-2235","post","type-post","status-publish","format-standard","hentry","category-python-language","tag-csv","tag-csv-writer","tag-python","tag-try-except"],"_links":{"self":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/2235","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/comments?post=2235"}],"version-history":[{"count":3,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/2235\/revisions"}],"predecessor-version":[{"id":2241,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/posts\/2235\/revisions\/2241"}],"wp:attachment":[{"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/media?parent=2235"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/categories?post=2235"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/bluegalaxy.info\/codewalk\/wp-json\/wp\/v2\/tags?post=2235"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}