{"id":126769,"date":"2022-07-23T07:42:24","date_gmt":"2022-07-23T07:42:24","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=505474"},"modified":"2022-07-23T07:42:24","modified_gmt":"2022-07-23T07:42:24","slug":"python-convert-string-to-csv-file","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/07\/23\/python-convert-string-to-csv-file\/","title":{"rendered":"Python Convert String to CSV File"},"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;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;}\">\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: 142.5px;\">\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;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2>Problem Formulation<\/h2>\n<p>Given a Python string:<\/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=\"\">my_string = '''a,b,c\n1,2,3\n9,8,7'''<\/pre>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Question<\/strong>: How to convert the string to a CSV file in Python?<\/p>\n<p>The desired output is the CSV file:<\/p>\n<p><code><strong>'my_file.csv'<\/strong><\/code>:<\/p>\n<pre class=\"wp-block-preformatted\"><code>a,b,c\n1,2,3\n9,8,7<\/code><\/pre>\n<h2>Simple Vanilla Python Solution<\/h2>\n<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>\n<p>This works if the string is already in the correct CSV format with values separated by commas.<\/p>\n<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>\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=\"\">my_string = '''a,b,c\n1,2,3\n9,8,7''' with open('my_file.csv', 'w') as out: out.write(my_string)\n<\/pre>\n<p>The result is a file <code>'my_file.csv'<\/code> with the following contents:<\/p>\n<pre class=\"wp-block-preformatted\"><code>a,b,c\n1,2,3\n9,8,7<\/code><\/pre>\n<h2>Parsing and Modifying Text to CSV<\/h2>\n<p>The string may not be in the correct CSV format. <\/p>\n<p>For example, you may want to convert any of the following strings to a CSV file&#8212;their format is not yet ready for writing it directly in a comma-separated file (CSV):<\/p>\n<ol>\n<li><strong>Example 1<\/strong>: <code>'abc;123;987'<\/code><\/li>\n<li><strong>Example 2<\/strong>: <code>'abc 123 987'<\/code><\/li>\n<li><strong>Example 3<\/strong>: <code>'a=b=c 1=2=3 9=8=7'<\/code><\/li>\n<li>&#8230;<\/li>\n<\/ol>\n<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>\n<p>Let&#8217;s go over each of those examples to see how to parse the string effectively to bring it into the CSV format:<\/p>\n<h3>Example 1<\/h3>\n<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:\nmy_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)\n<\/pre>\n<p>I&#8217;ve higlighted the two code lines that convert the string to the CSV format. <\/p>\n<ul>\n<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>\n<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>\n<\/ul>\n<p>The output file <code>'my_file.csv'<\/code> contains the same CSV formatted text:<\/p>\n<pre class=\"wp-block-preformatted\"><code>a,b,c\n1,2,3\n9,8,7<\/code><\/pre>\n<h3>Example 2<\/h3>\n<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>\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=\"\"># Example 2:\nmy_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)\n<\/pre>\n<p>The output file <code>'my_file.csv'<\/code> contains the same CSV formatted text:<\/p>\n<pre class=\"wp-block-preformatted\"><code>a,b,c\n1,2,3\n9,8,7<\/code><\/pre>\n<h3>Example 3<\/h3>\n<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>\n<p>This is shown in the following example:<\/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=\"\"># Example 3:\nmy_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)\n<\/pre>\n<p>Thanks for reading this article! I appreciate the time you took to learn Python with me. <\/p>\n<p>If you&#8217;re interested in writing more concise code, feel free to check out my one-liner book here:<\/p>\n<h2>Python One-Liners Book: Master the Single Line First!<\/h2>\n<p><strong>Python programmers will improve their computer science skills with these useful one-liners.<\/strong><\/p>\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-medium is-resized\"><a href=\"https:\/\/www.amazon.com\/gp\/product\/B07ZY7XMX8\" target=\"_blank\" rel=\"noopener noreferrer\"><img loading=\"lazy\" decoding=\"async\" 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\/uploads\/2020\/06\/3D_cover-300x277.jpg 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2020\/06\/3D_cover-768x708.jpg 768w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/a><\/figure>\n<\/div>\n<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 &#8220;one-liners&#8221;: <strong><em>concise statements of useful functionality packed into a single line of code. <\/em><\/strong>You&#8217;ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.<\/p>\n<p>The book&#8217;s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms. <\/p>\n<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&#8217;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>\n<p>You&#8217;ll also learn how to:<\/p>\n<ul>\n<li>Leverage data structures to <strong>solve real-world problems<\/strong>, like using Boolean indexing to find cities with above-average pollution<\/li>\n<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>\n<li>Calculate basic <strong>statistics <\/strong>of multidimensional data arrays and the K-Means algorithms for unsupervised learning<\/li>\n<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>\n<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>\n<\/ul>\n<p>By the end of the book, you&#8217;ll know how to <strong><em>write Python at its most refined<\/em><\/strong>, and create concise, beautiful pieces of &#8220;Python art&#8221; in merely a single line.<\/p>\n<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>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) Problem Formulation Given a Python string: my_string = &#8221;&#8217;a,b,c 1,2,3 9,8,7&#8221;&#8217; Question: How to convert the string to a CSV file in Python? The desired output is the CSV file: &#8216;my_file.csv&#8217;: a,b,c 1,2,3 9,8,7 Simple Vanilla Python Solution To convert a multi-line string with comma-separated values to a CSV file in [&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-126769","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\/126769","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=126769"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/126769\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=126769"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=126769"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=126769"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}