[Tut] Python Convert CSV to Text File (.csv to .txt) - Printable Version +- Sick Gaming (https://www.sickgaming.net) +-- Forum: Programming (https://www.sickgaming.net/forum-76.html) +--- Forum: Python (https://www.sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Convert CSV to Text File (.csv to .txt) (/thread-99634.html) |
[Tut] Python Convert CSV to Text File (.csv to .txt) - xSicKxBot - 06-25-2022 Python Convert CSV to Text File (.csv to .txt) <div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{"align":"left","id":"439023","slug":"default","valign":"top","reference":"auto","count":"1","readonly":"","score":"5","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})"}"> <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: 142.5px;"> <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"> 5/5 – (1 vote) </div> </div> <h2>Basic Challenge</h2> </p> <p>Here’s the content of an example CSV file <code>"my_file.csv"</code> used in our code snippet below:</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000</pre> <p>If you visualize this CSV in table form, it looks like this:</p> <figure class="wp-block-table is-style-stripes"> <table> <thead> <tr> <th>Name</th> <th>Job</th> <th>Age</th> <th>Income</th> </tr> </thead> <tbody> <tr> <td>Alice</td> <td>Programmer</td> <td>23</td> <td>110000</td> </tr> <tr> <td>Bob</td> <td>Executive</td> <td>34</td> <td>90000</td> </tr> <tr> <td>Carl</td> <td>Sales</td> <td>45</td> <td>50000</td> </tr> </tbody> </table> </figure> <p>The basic problem is to convert the CSV file <code>"my_file.csv"</code> to a new TXT file <code>"my_file.txt"</code> as is without changing its content</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000</pre> <p>We start with exploring this basic challenge and build from there by changing the delimiter and using Pandas to access individual columns.</p> <p>But first things first: <strong><em>How to convert a CSV file to a TXT file without changing its contents?</em></strong></p> <h2>Method 1: CSV to TXT Unchanged</h2> <p class="has-global-color-8-background-color has-background">If you want to keep the content (including the delimiter <code>','</code>) in the CSV file unmodified, the conversion is simple: read the <code>.csv</code> file and write its content into a new <code>.txt</code> file using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-open-function/" data-type="post" data-id="24793" target="_blank">open()</a></code>, <code><a href="https://blog.finxter.com/python-read-binary-file/" data-type="post" data-id="36231" target="_blank" rel="noreferrer noopener">read()</a></code>, and <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-liner-write-string-to-file/" data-type="post" data-id="10913" target="_blank">write()</a></code> functions without importing any library.</p> <p>In other words, perform the three steps to write a CSV to a TXT file unmodified:</p> <ol> <li>Open the CSV file in reading mode and the TXT file in writing mode.</li> <li>Read the CSV file and store it in a variable.</li> <li>Write the content into the TXT file.</li> </ol> <p>Here’s the code snippet that solves our basic challenge:</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=""># 1. Open the CSV file in reading mode and the TXT file in writing mode with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: # 2. Read the CSV file and store in variable content = f_in.read() # 3. Write the content into the TXT file f_out.write(content)</pre> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f632.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Little-Known Fact</strong>: Python allows <em>multiple expressions</em> in the <a href="https://blog.finxter.com/how-to-open-multiple-files-in-python/" data-type="post" data-id="403242" target="_blank" rel="noreferrer noopener">context manager</a> (<code>with</code> opening line) if you separate them with a comma. </p> <p>The content of the <code>.csv</code> and <code>.txt</code> files is identical:</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000</pre> <p>So far, so good. But what if you have a slightly different problem:</p> <h2>Method 2: CSV to TXT Empty Space Delimiter</h2> <p><strong>Challenge</strong>: How to convert a CSV file to a TXT file in Python by replacing the delimiter <code>','</code> with the empty space <code>' '</code>?</p> <p><strong>Example</strong>: Convert the following file <code>'my_file.csv'</code>…</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Name,Job,Age,Income Alice,Programmer,23,110000 Bob,Executive,34,90000 Carl,Sales,45,50000</pre> <p>… to this file <code>'my_file.txt'</code> …</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Name Job Age Income Alice Programmer 23 110000 Bob Executive 34 90000 Carl Sales 45 50000</pre> <p>Here’s the simple solution to this challenge:</p> <p class="has-global-color-8-background-color has-background">If you want to change the delimiter <code>','</code> to an empty string <code>' '</code> in the new TXT file, read the <code>.csv</code> file and write its content into a new <code>.txt</code> file using the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-open-function/" data-type="post" data-id="24793" target="_blank">open()</a></code>, <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-read-binary-file/" data-type="post" data-id="36231" target="_blank">read()</a></code>, <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-replace-2/" data-type="post" data-id="26083" target="_blank">string.replace()</a></code>, and <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-liner-write-string-to-file/" data-type="post" data-id="10913" target="_blank">write()</a></code> functions without importing any library.</p> <p>To convert a CSV to a TXT file in Python, perform the following steps:</p> <ol> <li>Open the CSV file in reading mode and the TXT file in writing mode.</li> <li>Read the CSV file into a string.</li> <li>Create a new string by replacing all occurrences of the delimiter <code>','</code> with the empty string <code>' '</code>. </li> <li>Write the content into the TXT file.</li> </ol> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="2" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">with open('my_file.csv', 'r') as f_in, open('my_file.txt', 'w') as f_out: content = f_in.read().replace(',', ' ') f_out.write(content) </pre> <p>So far, so good. But in Python, there are always many ways to solve a problem. Let’s have a look at a powerful alternative to the no-library approach used before:</p> <h2>Method 3: CSV to TXT using Pandas</h2> <p>Assuming you’ve already <a href="https://blog.finxter.com/how-to-install-pandas-in-python/" data-type="post" data-id="35926" target="_blank" rel="noreferrer noopener">installed pandas</a> in your local environment, you can write a <strong>CSV to a TXT file in Python pandas</strong> using the following four steps:</p> <ol class="has-base-background-color has-background"> <li>Import the <code><a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511">pan</a><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank">d</a><a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511">as</a></code> library.</li> <li>Read the CSV file into a DataFrame using <code><a rel="noreferrer noopener" href="https://blog.finxter.com/read-and-write-flat-files-with-pandas/" data-type="post" data-id="62847" target="_blank">pd.read_csv()</a></code>.</li> <li>Convert the DataFrame to a String using the built-in <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-str-function/" data-type="URL" data-id="https://blog.finxter.com/python-str-function/" target="_blank">str()</a></code> function.</li> <li>Print the string to a file using the file argument of the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank">print()</a></code> function, for example.</li> </ol> <p>Here’s the basic Python example:</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="">import pandas as pd df = pd.read_csv('my_file.csv') content = str(df) print(content, file=open('my_file.txt', 'w'))</pre> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f632.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Little-Known Fact</strong>: Python’s <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank">print()</a></code> function allows you to write a <a rel="noreferrer noopener" href="https://blog.finxter.com/python-one-liner-write-string-to-file/" data-type="post" data-id="10913" target="_blank">string directly into a file </a>object if you use the <code>file</code> argument as shown in the code snippet.</p> <p>The output of the previous code snippet is as follows:</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> Name Job Age Income 0 Alice Programmer 23 110000 1 Bob Executive 34 90000 2 Carl Sales 45 50000</pre> <p>Beautiful, isn’t it? <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f49c.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p> <p>Let’s have a look at the last variation of the “CSV to TXT” problem addressed in this tutorial:</p> <h2>Method 4: CSV Columns or Rows to TXT using Pandas</h2> <p><strong>How to write one or more individual columns or rows of the CSV file into a TXT file using Python Pandas?</strong></p> <ol class="has-base-background-color has-background"> <li>Import the <code><a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511">pan</a><a rel="noreferrer noopener" href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511" target="_blank">d</a><a href="https://blog.finxter.com/pandas-quickstart/" data-type="post" data-id="16511">as</a></code> library.</li> <li>Read the CSV file into a DataFrame using <code><a rel="noreferrer noopener" href="https://blog.finxter.com/read-and-write-flat-files-with-pandas/" data-type="post" data-id="62847" target="_blank">pd.read_csv()</a></code>.</li> <li>Select the column(s) or row(s) to write into the TXT file from the DataFrame using <a href="https://blog.finxter.com/pandas-dataframe-indexing/" data-type="post" data-id="64801" target="_blank" rel="noreferrer noopener">Pandas indexing or slicing</a>.</li> <li>Call <code>df.to_string()</code> to convert the DataFrame to a string in a human-readable way.</li> <li>Print the string to a file using the file argument of the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-print/" data-type="URL" data-id="https://blog.finxter.com/python-print/" target="_blank">print()</a></code> function, for example.</li> </ol> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd df = pd.read_csv('my_file.csv') content = str(df['Name']) print(content, file=open('my_file.txt', 'w'))</pre> <p>The content in a new file <code>'my_file.txt'</code>:</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0 Alice 1 Bob 2 Carl</pre> <p>Of course, you can also select individual rows or multiple columns like so:</p> <pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="4" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import pandas as pd df = pd.read_csv('my_file.csv') content = df['Name'][:2].to_string() print(content, file=open('my_file.txt', 'w'))</pre> <p>The content of the new file <code>'my_file.txt'</code> shows that only the first two rows have been taken due to the <a rel="noreferrer noopener" href="https://blog.finxter.com/slicing-data-from-a-pandas-dataframe-using-loc-and-iloc/" data-type="post" data-id="230997" target="_blank">slicing</a> operation <code>[:2]</code> in the previous code snippet:</p> <pre class="EnlighterJSRAW" data-enlighter-language="raw" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">0 Alice 1 Bob</pre> <p>Done! You’ve earned some programming enjoyment:</p> <h2>Programmer Humor</h2> <p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2753.png" alt="❓" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <code><strong>Question:</strong> How did the programmer <strong><em>die</em></strong> in the shower? ☠</p> <p>❗ <strong>Answer</strong>: They read the shampoo bottle instructions: <br /><em><strong>Lather. Rinse. Repeat.</strong></em></code></p> <h2>Conclusion</h2> <p>I hope you enjoyed reading this article and learned something new. Feel free to join our email newsletter with free cheat sheets and weekly Python tutorials:</p> </div> https://www.sickgaming.net/blog/2022/06/25/python-convert-csv-to-text-file-csv-to-txt/ |