Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Convert Tuples to a CSV File in Python [4 Ways]

#1
How to Convert Tuples to a CSV File in Python [4 Ways]

<div><p><strong>Problem</strong>: How to convert one or more tuples to a <code>csv</code> file? </p>
<p><strong>Example</strong>: Given is a <a rel="noreferrer noopener" href="https://blog.finxter.com/the-ultimate-guide-to-python-tuples/" data-type="post" data-id="12043" target="_blank">tuple</a> or <a href="https://blog.finxter.com/convert-list-of-tuples-to-string/" data-type="post" data-id="9230">list of tuples</a>—for example, salary data of employees in a given company:</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="">salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)]</pre>
<p>Your goal is to write the content of the list of tuples into a <a rel="noreferrer noopener" href="https://en.wikipedia.org/wiki/Comma-separated_values" target="_blank">comma-separated-values</a> (CSV) file format. Your out file should look like this:</p>
<pre class="wp-block-preformatted"><code><strong><em># file.csv</em></strong>
Alice,Data Scientist,122000
Bob,Engineer,77000
Ann,Manager,119000</code></pre>
<p>Note that writing a <em><strong>single tuple</strong></em> to a CSV is a <strong>subproblem</strong> of writing <strong><em>multiple tuples</em></strong> to a CSV that can be easily solved by passing a list with a single tuple as an input to any function we’ll discuss in the article.</p>
<p><strong>Solution: </strong>There are four simple ways to convert a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-lists/" target="_blank">list</a> of tuples to a CSV file in <a rel="noreferrer noopener" href="https://blog.finxter.com/python-cheat-sheets/" target="_blank">Python</a>.</p>
<ol>
<li><strong>CSV</strong>: Import the <code>csv</code> <a rel="noreferrer noopener" href="https://docs.python.org/3/library/csv.html" target="_blank">module</a> in Python, create a csv writer object, and write the list of tuples to the file in using the <code>writerows()</code> method on the writer object.</li>
<li><strong>Pandas</strong>: Import the <a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-cheat-sheets/" target="_blank">pandas library</a>, create a Pandas DataFrame, and write the DataFrame to a file using the DataFrame method <code>DataFrame.to_csv('file.csv')</code>.</li>
<li><strong>NumPy</strong>: Import the <a rel="noreferrer noopener" href="https://blog.finxter.com/collection-10-best-numpy-cheat-sheets-every-python-coder-must-own/" target="_blank">NumPy library</a>, create a NumPy array, and write the output to a CSV file using the <code>numpy.savetxt('file.csv', array, delimiter=',')</code> method.</li>
<li><strong>Python</strong>: Use a pure <a rel="noreferrer noopener" href="https://blog.finxter.com/python-crash-course/" target="_blank">Python</a> implementation that doesn’t require any library by using the Python file I/O functionality.</li>
</ol>
<p>My preference is method 2 (<strong>Pandas</strong>) because it’s simplest to use and most robust for different input types (numerical or textual). </p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f9e9.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Try It Yourself: </strong>Before we dive into these <a rel="noreferrer noopener" href="https://blog.finxter.com/python-list-methods-cheat-sheet-instant-pdf-download/" target="_blank">methods </a>in more detail, feel free to play with them in our interactive code shell. Simply click the “Run” button and find the generated CSV files in the “Files” tab. </p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://colab.research.google.com/drive/1oQ1ArjwnULs5BrvBU8tkoamJZ41lnUa9?usp=sharing" target="_blank" rel="noopener"><img loading="lazy" width="839" height="704" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-258.png" alt="" class="wp-image-330378" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-258.png 839w, https://blog.finxter.com/wp-content/uplo...00x252.png 300w, https://blog.finxter.com/wp-content/uplo...68x644.png 768w" sizes="(max-width: 839px) 100vw, 839px" /></a><figcaption><strong>Try It Yourself</strong>: <a href="https://colab.research.google.com/drive/1oQ1ArjwnULs5BrvBU8tkoamJZ41lnUa9?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1oQ1ArjwnULs5BrvBU8tkoamJZ41lnUa9?usp=sharing" target="_blank" rel="noreferrer noopener">Click</a> to run in interactive shell!</figcaption></figure>
</div>
<p>Do you want to develop the skills of a <strong>well-rounded Python professional</strong>—while getting paid in the process? Become a Python freelancer and order your book <a href="https://amzn.to/2Re2JqO" target="_blank" rel="noreferrer noopener"><strong>Leaving the Rat Race with Python</strong></a> on Amazon (<em>Kindle/Print</em>)!</p>
<div class="wp-block-image">
<figure class="aligncenter size-medium is-resized"><a href="https://amzn.to/2Re2JqO" target="_blank" rel="noopener noreferrer"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-200x300.jpg" alt="Leaving the Rat Race with Python Book" class="wp-image-11850" width="200" height="300" srcset="https://blog.finxter.com/wp-content/uploads/2020/08/final_cover-200x300.jpg 200w, https://blog.finxter.com/wp-content/uplo...scaled.jpg 683w, https://blog.finxter.com/wp-content/uplo...8x1152.jpg 768w, https://blog.finxter.com/wp-content/uplo...4x1536.jpg 1024w, https://blog.finxter.com/wp-content/uplo...5x2048.jpg 1365w, https://blog.finxter.com/wp-content/uplo...50x225.jpg 150w" sizes="(max-width: 200px) 100vw, 200px" /></a></figure>
</div>
<h2>Method 1: Python’s CSV Module</h2>
<p>You can convert a list of tuples to a CSV file in Python easily—by using the <a rel="noreferrer noopener" href="https://docs.python.org/3/library/csv.html" target="_blank"><code>csv</code></a> library. <strong>This is the most customizable of all four methods.</strong></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="">salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)] # Method 1
import csv
with open('file.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writerows(salary)</pre>
<p>Output:</p>
<pre class="wp-block-preformatted"><code><strong><em># file.csv</em></strong>
Alice,Data Scientist,122000
Bob,Engineer,77000
Ann,Manager,119000</code></pre>
<p>In the code, you first open the file using Python’s standard <code><a href="https://blog.finxter.com/python-open-function/" data-type="post" data-id="24793" target="_blank" rel="noreferrer noopener">open()</a></code> command. Now, you can write content to the file object <code>f</code>. </p>
<p>Next, you pass this file object to the constructor of the CSV writer that implements some additional helper method—and effectively wraps the file object providing you with new CSV-specific functionality such as the <code>writerows()</code> method. </p>
<p>You now pass a list of tuples to the <code>writerows()</code> method of the CSV writer that takes care of converting the list of tuples to a CSV format. </p>
<p>You can customize the CSV writer in its constructor (e.g., by modifying the delimiter from a comma <code>','</code> to a whitespace <code>' '</code> character). Have a look at the specification to learn about <a rel="noreferrer noopener" href="https://docs.python.org/3/library/csv.html" target="_blank">advanced modifications</a>. </p>
<h2>Method 2: Pandas DataFrame to_csv()</h2>
<figure class="wp-block-image size-large"><img loading="lazy" width="1024" height="576" src="https://blog.finxter.com/wp-content/uploads/2022/04/list_of_tuples_to_csv-1024x576.jpg" alt="List of Tuples to CSV" class="wp-image-330383" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/list_of_tuples_to_csv-1024x576.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x169.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x432.jpg 768w, https://blog.finxter.com/wp-content/uplo...to_csv.jpg 1280w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
<p>You can convert a tuple or list of tuples to a<a rel="noreferrer noopener" href="https://pandas.pydata.org/" target="_blank"> Pandas</a> DataFrame that provides you with powerful capabilities such as the <a rel="noreferrer noopener" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" target="_blank"><code>to_csv()</code> method</a>. <strong>This is the easiest method and it allows you to avoid importing yet another library</strong> (I use Pandas in many Python projects anyways). </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="">salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)] # Method 2
import pandas as pd
df = pd.DataFrame(salary)
df.to_csv('file2.csv', index=False, header=False)</pre>
<p>Output:</p>
<pre class="wp-block-preformatted"><code><strong><em># file2.csv</em></strong>
Alice,Data Scientist,122000
Bob,Engineer,77000
Ann,Manager,119000</code></pre>
<p>You create a <a href="https://blog.finxter.com/how-to-create-a-dataframe-in-pandas/" data-type="post" data-id="16764" target="_blank" rel="noreferrer noopener">Pandas DataFrame</a>—which is Python’s default representation of tabular data. Think of it as an Excel spreadsheet within your code (with rows and columns). </p>
<p>The DataFrame is a very powerful data structure that allows you to perform various methods. One of those is the <code>to_csv()</code> method that allows you to write its contents into a CSV file.</p>
<p>You set the <code>index</code> and <code>header</code> arguments of the <code>to_csv()</code> method to <code>False</code> because Pandas, per default, adds integer row and column indices 0, 1, 2, …. </p>
<p>Again, think of them as the row and column indices in your Excel spreadsheet. You don’t want them to appear in the CSV file so you set the arguments to <code>False</code>. </p>
<p>If you want to customize the CSV output, you’ve got a lot of special arguments to play with. Check out <a rel="noreferrer noopener" href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html" target="_blank">this </a>article for a comprehensive list of all arguments.</p>
<figure class="wp-block-image size-full"><a href="https://blog.finxter.com/pandas-cheat-sheets/" target="_blank" rel="noopener"><img loading="lazy" width="741" height="573" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-257.png" alt="" class="wp-image-329079" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-257.png 741w, https://blog.finxter.com/wp-content/uplo...00x232.png 300w" sizes="(max-width: 741px) 100vw, 741px" /></a></figure>
<p><strong>Related article</strong>:<a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-cheat-sheets/" target="_blank"> Pandas Cheat Sheets to Pin to Your Wall</a></p>
<h2>Method 3: NumPy savetext()</h2>
<p><a rel="noreferrer noopener" href="https://blog.finxter.com/numpy-tutorial/" target="_blank">NumPy </a>is at the core of Python’s <a href="https://blog.finxter.com/freelance-data-science/" data-type="post" data-id="16658" target="_blank" rel="noreferrer noopener">data science</a> and <a href="https://blog.finxter.com/machine-learning-engineer-income-and-opportunity/" data-type="post" data-id="306050" target="_blank" rel="noreferrer noopener">machine learning</a> functionality. Even Pandas uses NumPy arrays to implement critical functionality.</p>
<p>You can convert a list of tuples to a CSV file by using <a rel="noreferrer noopener" href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.savetxt.html" target="_blank">NumPy’s <code>savetext()</code> function</a> and passing the NumPy array as an argument that arises from the conversion of the list of tuples. </p>
<p><strong>This method is best if you have numerical data only—otherwise, it’ll lead to complicated data type conversions which are not recommended.</strong></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="">a = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] # Method 3
import numpy as np
a = np.array(a)
np.savetxt('file3.csv', a, delimiter=',')</pre>
<p>Output:</p>
<pre class="wp-block-preformatted"><code><strong><em># file3.csv</em></strong>
1.000000000000000000e+00,2.000000000000000000e+00,3.000000000000000000e+00
4.000000000000000000e+00,5.000000000000000000e+00,6.000000000000000000e+00
7.000000000000000000e+00,8.000000000000000000e+00,9.000000000000000000e+00</code></pre>
<p>The output doesn’t look pretty: it stores the values as floats. But no worries, you can reformat the output using the format argument <code>fmt</code> of the <code>savetxt()</code> method (<a rel="noreferrer noopener" href="https://numpy.org/doc/stable/reference/generated/numpy.savetxt.html?highlight=save#numpy.savetxt" target="_blank">more here</a>). However, I’d recommend you stick to method 2 (Pandas) to avoid unnecessary complexity in your code.</p>
<h2>Method 4: Pure Python Without External Dependencies</h2>
<p>If you don’t want to import any library and still convert a list of tuples into a CSV file, you can use standard Python implementation as well: it’s not complicated and efficient. However, if possible you should rely on libraries that do the job for you. </p>
<p><strong>This method is best if you won’t or cannot use external dependencies.</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">salary = [('Alice', 'Data Scientist', 122000), ('Bob', 'Engineer', 77000), ('Ann', 'Manager', 119000)] # Method 4
with open('file4.csv','w') as f: for row in salary: for x in row: f.write(str(x) + ',') f.write('\n')</pre>
<p>Output:</p>
<pre class="wp-block-preformatted"><code><strong><em># file4.csv</em></strong>
Alice,Data Scientist,122000,
Bob,Engineer,77000,
Ann,Manager,119000,</code></pre>
<p>In the code, you first open the file object <code>f</code>. Then you iterate over each row and each element in the row and write the element to the file—one by one. After each element, you place the comma to generate the CSV file format. After each row, you place the newline character <code>'\n'</code>. </p>
<p><strong>Note</strong>: to get rid of the trailing comma, you can check if the element <code>x</code> is the last element in the row within the loop body and skip writing the comma if it is.</p>
<p><strong>Related</strong>: <a rel="noreferrer noopener" href="https://blog.finxter.com/subscribe/" target="_blank">Join the Finxter community and download your 8+ Python cheat sheets to refresh your code understanding.</a></p>
<h2>Related Video</h2>
<p>The following video shows how to convert a list of lists to a CSV in Python, converting a tuple or list of tuples will be similar:</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="How to Convert a List of Lists to a CSV File in Python" width="780" height="439" src="https://www.youtube.com/embed/-ewNMpo_LqU?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>Where to Go From Here?</h2>
<p>Enough theory. Let’s get some practice!</p>
<p>Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation. </p>
<p>To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>You build high-value coding skills by working on practical coding projects!</strong></p>
<p>Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f680.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> If your answer is <strong><em>YES!</em></strong>, consider becoming a <a rel="noreferrer noopener" href="https://blog.finxter.com/become-python-freelancer-course/" data-type="page" data-id="2072" target="_blank">Python freelance developer</a>! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>If you just want to learn about the freelancing opportunity, feel free to watch my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and learn how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p></p>
</div>


https://www.sickgaming.net/blog/2022/04/...on-4-ways/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016