08-18-2022, 10:44 AM
How to Append a New Row to a CSV File in Python?
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"570641","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"0","readonly":"","score":"0","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","width":"0","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<h2>Python Append Row to CSV</h2>
<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>
<p>Given the following file <code>'my_file.csv'</code>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" 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/uplo...00x226.png 300w" sizes="(max-width: 573px) 100vw, 573px" /></figure>
</div>
<p>You can append a row (dict) to the CSV file via this code snippet:</p>
<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)
row = {'A':'Y1', 'B':'Y2', 'C':'Y3'} # Open the CSV file in "append" mode
with 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)
</pre>
<p>After running the code in the same folder as your original <code>'my_file.csv'</code>, you’ll see the following result:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img 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/uplo...00x224.png 300w" sizes="(max-width: 576px) 100vw, 576px" /></figure>
</div>
<h2>Append Multiple Rows to CSV</h2>
<p>Given the following CSV file:</p>
<figure class="wp-block-image size-full"><img 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/uplo...00x229.png 300w" sizes="(max-width: 571px) 100vw, 571px" /></figure>
<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>
<p class="has-contrast-color has-text-color">Here’s an example (major changes highlighted):</p>
<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)
rows = [{'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
with 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)
</pre>
<p>The resulting CSV file has all three rows added to the first row:</p>
<figure class="wp-block-image size-full"><img 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/uplo...00x228.png 300w" sizes="(max-width: 572px) 100vw, 572px" /></figure>
<h2>Python Add Row to CSV Pandas</h2>
<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>
<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>
<p>For a full example, check out this code snippet:</p>
<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
rows = [{'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
df = pd.DataFrame(rows)
df.to_csv('my_file.csv', header=False, index=False) # Create another row and append row (as df) to existing CSV
row = [{'A':'X1', 'B':'X2', 'C':'X3'}]
df = pd.DataFrame(row)
df.to_csv('my_file.csv', mode='a', header=False, index=False)
</pre>
<p>The output file looks like this (new row highlighted):</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img 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/uplo...00x208.png 300w" sizes="(max-width: 577px) 100vw, 577px" /></figure>
</div>
<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>
<p>Here’s an example snippet for copy&paste:</p>
<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>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" 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>
</div>
https://www.sickgaming.net/blog/2022/08/...in-python/
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload="{"align":"left","id":"570641","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"0","readonly":"","score":"0","best":"5","gap":"5","greet":"Rate this post","legend":"0\/5 - (0 votes)","size":"24","width":"0","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 0px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> <span class="kksr-muted">Rate this post</span> </div>
</div>
<h2>Python Append Row to CSV</h2>
<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>
<p>Given the following file <code>'my_file.csv'</code>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" 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/uplo...00x226.png 300w" sizes="(max-width: 573px) 100vw, 573px" /></figure>
</div>
<p>You can append a row (dict) to the CSV file via this code snippet:</p>
<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)
row = {'A':'Y1', 'B':'Y2', 'C':'Y3'} # Open the CSV file in "append" mode
with 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)
</pre>
<p>After running the code in the same folder as your original <code>'my_file.csv'</code>, you’ll see the following result:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img 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/uplo...00x224.png 300w" sizes="(max-width: 576px) 100vw, 576px" /></figure>
</div>
<h2>Append Multiple Rows to CSV</h2>
<p>Given the following CSV file:</p>
<figure class="wp-block-image size-full"><img 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/uplo...00x229.png 300w" sizes="(max-width: 571px) 100vw, 571px" /></figure>
<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>
<p class="has-contrast-color has-text-color">Here’s an example (major changes highlighted):</p>
<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)
rows = [{'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
with 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)
</pre>
<p>The resulting CSV file has all three rows added to the first row:</p>
<figure class="wp-block-image size-full"><img 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/uplo...00x228.png 300w" sizes="(max-width: 572px) 100vw, 572px" /></figure>
<h2>Python Add Row to CSV Pandas</h2>
<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>
<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>
<p>For a full example, check out this code snippet:</p>
<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
rows = [{'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
df = pd.DataFrame(rows)
df.to_csv('my_file.csv', header=False, index=False) # Create another row and append row (as df) to existing CSV
row = [{'A':'X1', 'B':'X2', 'C':'X3'}]
df = pd.DataFrame(row)
df.to_csv('my_file.csv', mode='a', header=False, index=False)
</pre>
<p>The output file looks like this (new row highlighted):</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img 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/uplo...00x208.png 300w" sizes="(max-width: 577px) 100vw, 577px" /></figure>
</div>
<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>
<p>Here’s an example snippet for copy&paste:</p>
<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>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f30d.png" alt="?" 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>
</div>
https://www.sickgaming.net/blog/2022/08/...in-python/