07-26-2022, 12:21 PM
Python Convert String to CSV File
5/5 – (1 vote)
Problem Formulation
Given a Python string:
Question: How to convert the string to a CSV file in Python?
The desired output is the CSV file:
:
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) 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 function and the functions to write the multi-line string to a file without modification.
The result is a file with the following contents:
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):
To parse such a string and modify it before writing it in a file, you can use the and 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
I’ve higlighted the two code lines that convert the string to the CSV format.
The output file contains the same CSV formatted text:
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:
The output file contains the same CSV formatted text:
Example 3
If the comma-separated values are not yet comma-separated (e.g., they may be semicolon-separated), you can use the method to replace the symbols accordingly.
This is shown in the following example:
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.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill 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:
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!!
5/5 – (1 vote)
Problem Formulation
Given a Python string:
Code:
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:
Code:
'my_file.csv'Code:
a,b,c
1,2,3
9,8,7To 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
Code:
'my_file.csv'This works if the string is already in the correct CSV format with values separated by commas.
The following code uses the
Code:
open()Code:
file.write()Code:
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
Code:
'my_file.csv'Code:
a,b,c
1,2,3
9,8,7The 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):
- Example 1: Code:
'abc;123;987'
- Example 2: Code:
'abc 123 987'
- Example 3: Code:
'a=b=c 1=2=3 9=8=7'
- …
To parse such a string and modify it before writing it in a file
Code:
'my_file.csv'Code:
string.replace()Code:
string.split()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
Code:
# 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 function to bring those together to a CSV format that can be written into the output file.Code:
string.join()
The output file
Code:
'my_file.csv'Code:
a,b,c
1,2,3
9,8,7The following example is the same as the previous code snippet, only that the empty spaces
Code:
' 'Code:
# 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
Code:
'my_file.csv'Code:
a,b,c
1,2,3
9,8,7If the comma-separated values are not yet comma-separated (e.g., they may be semicolon-separated
Code:
'a;b;c'Code:
string.replace()This is shown in the following example:
Code:
# 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.
![[Image: 3D_cover-1024x944.jpg]](https://blog.finxter.com/wp-content/uploads/2020/06/3D_cover-1024x944.jpg)
Python One-Linerswill 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!!

