Create an account


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

#1
Python Convert String to CSV File

<div>
<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;505474&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&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;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}">
<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" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</div>
<h2>Problem Formulation</h2>
<p>Given a Python string:</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="">my_string = '''a,b,c
1,2,3
9,8,7'''</pre>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4ac.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: How to convert the string to a CSV file in Python?</p>
<p>The desired output is the CSV file:</p>
<p><code><strong>'my_file.csv'</strong></code>:</p>
<pre class="wp-block-preformatted"><code>a,b,c
1,2,3
9,8,7</code></pre>
<h2>Simple Vanilla Python Solution</h2>
<p class="has-global-color-8-background-color has-background">To convert a <a href="https://blog.finxter.com/multi-line-strings/" data-type="post" data-id="215" target="_blank" rel="noreferrer noopener">multi-line string</a> with comma-separated values to a CSV file in Python, simply write the string in a file (e.g., with the name <code>'my_file.csv'</code>) without further modification. </p>
<p>This works if the string is already in the correct CSV format with values separated by commas.</p>
<p>The following code uses 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> function and the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-convert-csv-to-text-file-csv-to-txt/" data-type="post" data-id="439023" target="_blank">file.write()</a></code> functions to write the multi-line string to a file without modification.</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="">my_string = '''a,b,c
1,2,3
9,8,7''' with open('my_file.csv', 'w') as out: out.write(my_string)
</pre>
<p>The result is a file <code>'my_file.csv'</code> with the following contents:</p>
<pre class="wp-block-preformatted"><code>a,b,c
1,2,3
9,8,7</code></pre>
<h2>Parsing and Modifying Text to CSV</h2>
<p>The string may not be in the correct CSV format. </p>
<p>For example, you may want to convert any of the following strings to a CSV file—their format is not yet ready for writing it directly in a comma-separated file (CSV):</p>
<ol>
<li><strong>Example 1</strong>: <code>'abc;123;987'</code></li>
<li><strong>Example 2</strong>: <code>'abc 123 987'</code></li>
<li><strong>Example 3</strong>: <code>'a=b=c 1=2=3 9=8=7'</code></li>
<li>…</li>
</ol>
<p>To parse such a string and modify it before writing it in a file <code>'my_file.csv'</code>, you can use the <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-string-split/" data-type="post" data-id="26097" target="_blank">string.split()</a></code> methods to make sure that each value is separated by a comma and each row has its own line.</p>
<p>Let’s go over each of those examples to see how to parse the string effectively to bring it into the CSV format:</p>
<h3>Example 1</h3>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="5-6" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Example 1:
my_string = 'abc;123;987' with open('my_file.csv', 'w') as out: lines = [','.join(line) for line in my_string.split(';')] my_string = '\n'.join(lines) out.write(my_string)
</pre>
<p>I’ve higlighted the two code lines that convert the string to the CSV format. </p>
<ul>
<li>The first highlighted line uses <a rel="noreferrer noopener" href="https://blog.finxter.com/list-comprehension/" data-type="post" data-id="1171" target="_blank">list comprehension</a> to create a list of three lines, each interleaved with a comma. </li>
<li>The second highlighted line uses the <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-join/" data-type="post" data-id="26062" target="_blank">string.join()</a></code> function to bring those together to a CSV format that can be written into the output file.</li>
</ul>
<p>The output file <code>'my_file.csv'</code> contains the same CSV formatted text:</p>
<pre class="wp-block-preformatted"><code>a,b,c
1,2,3
9,8,7</code></pre>
<h3>Example 2</h3>
<p>The following example is the same as the previous code snippet, only that the empty spaces <code>' '</code> in the input string should be converted to new lines to obtain the final CSV:</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=""># Example 2:
my_string = 'abc 123 987' with open('my_file.csv', 'w') as out: lines = [','.join(line) for line in my_string.split(' ')] my_string = '\n'.join(lines) out.write(my_string)
</pre>
<p>The output file <code>'my_file.csv'</code> contains the same CSV formatted text:</p>
<pre class="wp-block-preformatted"><code>a,b,c
1,2,3
9,8,7</code></pre>
<h3>Example 3</h3>
<p>If the comma-separated values are not yet comma-separated (e.g., they may be semicolon-separated <code>'a;b;c'</code>), you can use the <code><a href="https://blog.finxter.com/python-string-replace-2/" data-type="post" data-id="26083" target="_blank" rel="noreferrer noopener">string.replace()</a></code> method to replace the symbols accordingly.</p>
<p>This is shown in the following example:</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=""># Example 3:
my_string = 'a=b=c 1=2=3 9=8=7' with open('my_file.csv', 'w') as out: my_string = my_string.replace('=', ',').replace(' ', '\n') out.write(my_string)
</pre>
<p>Thanks for reading this article! I appreciate the time you took to learn Python with me. </p>
<p>If you’re interested in writing more concise code, feel free to check out my one-liner book here:</p>
<h2>Python One-Liners Book: Master the Single Line First!</h2>
<p><strong>Python programmers will improve their computer science skills with these useful one-liners.</strong></p>
<div class="wp-block-image">
<figure class="aligncenter size-medium is-resized"><a href="https://www.amazon.com/gp/product/B07ZY7XMX8" target="_blank" rel="noopener noreferrer"><img loading="lazy" src="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg" alt="Python One-Liners" class="wp-image-10007" width="512" height="472" srcset="https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-scaled.jpg 1024w, https://blog.finxter.com/wp-content/uplo...00x277.jpg 300w, https://blog.finxter.com/wp-content/uplo...68x708.jpg 768w" sizes="(max-width: 512px) 100vw, 512px" /></a></figure>
</div>
<p><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Python One-Liners</em> </a>will teach you how to read and write “one-liners”: <strong><em>concise statements of useful functionality packed into a single line of code. </em></strong>You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.</p>
<p>The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. </p>
<p>Detailed explanations of one-liners introduce <strong><em>key computer science concepts </em></strong>and<strong><em> boost your coding and analytical skills</em></strong>. You’ll learn about advanced Python features such as <em><strong>list comprehension</strong></em>, <strong><em>slicing</em></strong>, <strong><em>lambda functions</em></strong>, <strong><em>regular expressions</em></strong>, <strong><em>map </em></strong>and <strong><em>reduce </em></strong>functions, and <strong><em>slice assignments</em></strong>. </p>
<p>You’ll also learn how to:</p>
<ul>
<li>Leverage data structures to <strong>solve real-world problems</strong>, like using Boolean indexing to find cities with above-average pollution</li>
<li>Use <strong>NumPy basics</strong> such as <em>array</em>, <em>shape</em>, <em>axis</em>, <em>type</em>, <em>broadcasting</em>, <em>advanced indexing</em>, <em>slicing</em>, <em>sorting</em>, <em>searching</em>, <em>aggregating</em>, and <em>statistics</em></li>
<li>Calculate basic <strong>statistics </strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning</li>
<li>Create more <strong>advanced regular expressions</strong> using <em>grouping </em>and <em>named groups</em>, <em>negative lookaheads</em>, <em>escaped characters</em>, <em>whitespaces, character sets</em> (and <em>negative characters sets</em>), and <em>greedy/nongreedy operators</em></li>
<li>Understand a wide range of <strong>computer science topics</strong>, including <em>anagrams</em>, <em>palindromes</em>, <em>supersets</em>, <em>permutations</em>, <em>factorials</em>, <em>prime numbers</em>, <em>Fibonacci </em>numbers, <em>obfuscation</em>, <em>searching</em>, and <em>algorithmic sorting</em></li>
</ul>
<p>By the end of the book, you’ll know how to <strong><em>write Python at its most refined</em></strong>, and create concise, beautiful pieces of “Python art” in merely a single line.</p>
<p><strong><a href="https://amzn.to/2WAYeJE" target="_blank" rel="noreferrer noopener" title="https://amzn.to/2WAYeJE"><em>Get your Python One-Liners on Amazon!!</em></a></strong></p>
</div>


https://www.sickgaming.net/blog/2022/07/...-csv-file/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016