Python Convert String to CSV File

5/5 - (3 votes)

Problem Formulation

Given a Python string:

my_string = '''a,b,c
1,2,3
9,8,7'''

💬 Question: How to convert the string to a CSV file in Python?

The desired output is the CSV file:

'my_file.csv':

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 Python, simply write the string in a file (e.g., with the name 'my_file.csv') without further modification.

This works if the string is already in the correct CSV format with values separated by commas.

The following code uses the open() function and the file.write() functions to write the multi-line string to a file without modification.

my_string = '''a,b,c
1,2,3
9,8,7'''

with open('my_file.csv', 'w') as out:
    out.write(my_string)

The result is a file 'my_file.csv' with the following contents:

a,b,c
1,2,3
9,8,7

Parsing and Modifying Text to CSV

The string may not be in the correct CSV format.

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):

  1. Example 1: 'abc;123;987'
  2. Example 2: 'abc 123 987'
  3. Example 3: 'a=b=c 1=2=3 9=8=7'

To parse such a string and modify it before writing it in a file 'my_file.csv', you can use the string.replace() and string.split() methods to make sure that each value is separated by a comma and each row has its own line.

Let’s go over each of those examples to see how to parse the string effectively to bring it into the CSV format:

Example 1

# 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)

I’ve higlighted the two code lines that convert the string to the CSV format.

  • The first highlighted line uses list comprehension to create a list of three lines, each interleaved with a comma.
  • The second highlighted line uses the string.join() function to bring those together to a CSV format that can be written into the output file.

The output file 'my_file.csv' contains the same CSV formatted text:

a,b,c
1,2,3
9,8,7

Example 2

The following example is the same as the previous code snippet, only that the empty spaces ' ' in the input string should be converted to new lines to obtain the final CSV:

# 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)

The output file 'my_file.csv' contains the same CSV formatted text:

a,b,c
1,2,3
9,8,7

Example 3

If the comma-separated values are not yet comma-separated (e.g., they may be semicolon-separated 'a;b;c'), you can use the string.replace() method to replace the symbols accordingly.

This is shown in the following example:

# 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)

Thanks for reading this article! I appreciate the time you took to learn Python with me.

If you’re interested in writing more concise code, feel free to check out my one-liner book here:

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

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.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!