{"id":127273,"date":"2022-08-14T14:11:02","date_gmt":"2022-08-14T14:11:02","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=570641"},"modified":"2022-08-14T14:11:02","modified_gmt":"2022-08-14T14:11:02","slug":"how-to-append-a-new-row-to-a-csv-file-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/08\/14\/how-to-append-a-new-row-to-a-csv-file-in-python\/","title":{"rendered":"How to Append a New Row to a CSV File in Python?"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;570641&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;0&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;0&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;0\\\/5 - (0 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;0&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 0px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> <span class=\"kksr-muted\">Rate this post<\/span> <\/div>\n<\/div>\n<h2>Python Append Row to CSV<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">To append a row (=<a href=\"https:\/\/blog.finxter.com\/python-dictionary\/\" data-type=\"post\" data-id=\"5232\" target=\"_blank\" rel=\"noreferrer noopener\">dictionary<\/a>) to an existing CSV, <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-open-function\/\" data-type=\"post\" data-id=\"24793\" target=\"_blank\">open<\/a> the file object in <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/append-to-a-file-python\/\" data-type=\"post\" data-id=\"206350\" target=\"_blank\">append mode<\/a> using <code>open('my_file.csv', 'a', newline='')<\/code>. Then create a <code>csv.DictWriter()<\/code> to append a dict row using <code>DictWriter.writerow(my_dict)<\/code>.<\/p>\n<p>Given the following file <code>'my_file.csv'<\/code>:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"573\" height=\"432\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-31.png\" alt=\"\" class=\"wp-image-570620\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-31.png 573w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-31-300x226.png 300w\" sizes=\"auto, (max-width: 573px) 100vw, 573px\" \/><\/figure>\n<\/div>\n<p>You can append a row (dict) to the CSV file via this code snippet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"6,8\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import csv # Create the dictionary (=row)\nrow = {'A':'Y1', 'B':'Y2', 'C':'Y3'} # Open the CSV file in \"append\" mode\nwith open('my_file.csv', 'a', newline='') as f: # Create a dictionary writer with the dict keys as column fieldnames writer = csv.DictWriter(f, fieldnames=row.keys()) # Append single row to CSV writer.writerow(row)\n<\/pre>\n<p>After running the code in the same folder as your original <code>'my_file.csv'<\/code>, you&#8217;ll see the following result:<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"576\" height=\"430\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-32.png\" alt=\"\" class=\"wp-image-570628\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-32.png 576w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-32-300x224.png 300w\" sizes=\"auto, (max-width: 576px) 100vw, 576px\" \/><\/figure>\n<\/div>\n<h2>Append Multiple Rows to CSV<\/h2>\n<p>Given the following CSV file:<\/p>\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"571\" height=\"435\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-37.png\" alt=\"\" class=\"wp-image-573915\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-37.png 571w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-37-300x229.png 300w\" sizes=\"auto, (max-width: 571px) 100vw, 571px\" \/><\/figure>\n<p class=\"has-global-color-8-background-color has-background\">To add multiple rows (i.e., dicts) to an old existing CSV file, iterate over the rows and write each <code>row<\/code> by calling <code>csv.DictWriter.writerow(row)<\/code> on the initially created <code>DictWriter<\/code> object.<\/p>\n<p class=\"has-contrast-color has-text-color\">Here&#8217;s an example (major changes highlighted):<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"14-16\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import csv # Create the dictionary (=row)\nrows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'}, {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'}, {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}] # Open the CSV file in \"append\" mode\nwith open('my_file.csv', 'a', newline='') as f: # Create a dictionary writer with the dict keys as column fieldnames writer = csv.DictWriter(f, fieldnames=rows[0].keys()) # Append multiple rows to CSV for row in rows: writer.writerow(row)\n<\/pre>\n<p>The resulting CSV file has all three rows added to the first row:<\/p>\n<figure class=\"wp-block-image size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"572\" height=\"435\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-36.png\" alt=\"\" class=\"wp-image-573896\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-36.png 572w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-36-300x228.png 300w\" sizes=\"auto, (max-width: 572px) 100vw, 572px\" \/><\/figure>\n<h2>Python Add Row to CSV Pandas<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">To add a row to an existing CSV using Pandas, you can set the write <code>mode<\/code> argument to append <code>'a'<\/code> in the pandas DataFrame <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/pandas-dataframe-to_csv-method\/\" data-type=\"post\" data-id=\"344277\" target=\"_blank\">to_csv()<\/a><\/code> method like so: <code>df.to_csv('my_csv.csv', mode='a', header=False)<\/code>.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">df.to_csv('my_csv.csv', mode='a', header=False)<\/pre>\n<p>For a full example, check out this code snippet:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"12-15\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import pandas as pd # Create the initial CSV data\nrows = [{'A':'Z1', 'B':'Z2', 'C':'Z3'}, {'A':'ZZ1', 'B':'ZZ2', 'C':'ZZ3'}, {'A':'ZZZ1', 'B':'ZZZ2', 'C':'ZZZ3'}] # Create a DataFrame and write to CSV\ndf = pd.DataFrame(rows)\ndf.to_csv('my_file.csv', header=False, index=False) # Create another row and append row (as df) to existing CSV\nrow = [{'A':'X1', 'B':'X2', 'C':'X3'}]\ndf = pd.DataFrame(row)\ndf.to_csv('my_file.csv', mode='a', header=False, index=False)\n<\/pre>\n<p>The output file looks like this (new row highlighted):<\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img decoding=\"async\" loading=\"lazy\" width=\"577\" height=\"400\" src=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-38.png\" alt=\"\" class=\"wp-image-573962\" srcset=\"https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-38.png 577w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2022\/08\/image-38-300x208.png 300w\" sizes=\"auto, (max-width: 577px) 100vw, 577px\" \/><\/figure>\n<\/div>\n<p class=\"has-base-background-color has-background\">Alternatively, you can open the file in <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/append-to-a-file-python\/\" data-type=\"post\" data-id=\"206350\" target=\"_blank\">append mode<\/a> using normal <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-open-function\/\" data-type=\"post\" data-id=\"24793\" target=\"_blank\">open()<\/a><\/code> function with the append <code>'a'<\/code> argument and pass it into the pandas DataFrame <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/pandas-to_csv\/\" data-type=\"post\" data-id=\"8027\" target=\"_blank\">to_csv()<\/a><\/code> method.<\/p>\n<p>Here&#8217;s an example snippet for copy&amp;paste:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">with open('my_csv.csv', 'a') as f: df.to_csv(f, header=False)<\/pre>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f30d.png\" alt=\"\ud83c\udf0d\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Learn More<\/strong>: If you want to learn about 7 Best Ways to Convert Dict to CSV in Python, <a href=\"https:\/\/blog.finxter.com\/how-to-convert-dict-to-csv-in-python-4-ways\/\" data-type=\"post\" data-id=\"570412\" target=\"_blank\" rel=\"noreferrer noopener\">check out this Finxter tutorial<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Rate this post Python Append Row to CSV To append a row (=dictionary) to an existing CSV, open the file object in append mode using open(&#8216;my_file.csv&#8217;, &#8216;a&#8217;, newline=&#8221;). Then create a csv.DictWriter() to append a dict row using DictWriter.writerow(my_dict). Given the following file &#8216;my_file.csv&#8217;: You can append a row (dict) to the CSV file via [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-127273","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127273","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127273"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127273\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127273"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127273"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127273"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}