Skip to content

Instantly share code, notes, and snippets.

@flyte
Last active December 20, 2015 03:18
Show Gist options
  • Save flyte/6062230 to your computer and use it in GitHub Desktop.
Save flyte/6062230 to your computer and use it in GitHub Desktop.
Format a single value for use in an RFC4180 compliant CSV file. Join multiple of the values returned from this function with a comma to create a row.
def _format_csv_value(self, value):
"""Takes a single CSV value string and formats it in compliance with RFC4180.
Multiple values can be joined together by putting them in a list and using ",".join(the_list).
http://tools.ietf.org/html/rfc4180#page-3
:param value: A single value destined to be output among multiple in a CSV row
:return: The escaped and/or quoted string if necessary, otherwise simply returns <value>.
"""
for x in [",", '"', "\n", "\r\n"]:
if x in value:
# Must replace double quotes '"' with two double quotes '""'
value = value.replace('"', '""')
# and contain all fields in double quotes if they contain commas or double quotes
value = '"%s"' % value
break
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment