Created
April 21, 2020 12:06
-
-
Save sloev/1625dd0020bb84140afcb2d2cb741ef1 to your computer and use it in GitHub Desktop.
how to encode values to csv string in python 3 (args to csv string)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import csv | |
from io import StringIO | |
class ArgsToCsv: | |
def __init__(self, seperator=","): | |
self.seperator = seperator | |
self.buffer = StringIO() | |
self.writer = csv.writer(self.buffer) | |
def stringify(self, *args): | |
self.writer.writerow(args) | |
value = self.buffer.getvalue().strip("\r\n") | |
self.buffer.seek(0) | |
self.buffer.truncate(0) | |
return value + "\n" | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from args_to_csv import ArgsToCsv | |
csv_formatter = ArgsToCsv() | |
output = "" | |
header = ["age", "text", "my_array"] | |
output += csv_formatter.stringify(*header) | |
output += csv_formatter.stringify( | |
10, | |
""" | |
lol i have some pretty | |
"freaky" | |
strings right here \' yo! | |
""", | |
[10, 20, 30], | |
) | |
output += csv_formatter.stringify(10, "hi there", None) | |
assert output.splitlines() == [ | |
"age,text,my_array", | |
'10,"', | |
" lol i have some pretty", | |
' ""freaky""', | |
" strings right here ' yo!", | |
' ","[10, 20, 30]"', | |
"10,hi there,", | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sloev Thanks for the snippet. I think you forgot to use separator.