def CsvEscape(text):
  """Escapes data entry for consistency with CSV format.

  The CSV format rules:
    - Fields with embedded commas must be enclosed within double-quote
      characters.
    - Fields with embedded double-quote characters must be enclosed within
      double-quote characters, and each of the embedded double-quote characters
      must be represented by a pair of double-quote characters.
    - Fields with embedded line breaks must be enclosed within double-quote
      characters.
    - Fields with leading or trailing spaces must be enclosed within
      double-quote characters.

  Args:
    text: str Data entry.

  Returns:
    str CSV encoded data entry.
  """
  if not text: return ''
  if text.find('"') > -1: text = text.replace('"', '""')
  if (text == '' or text.find(',') > -1 or text.find('"') > -1 or
      text.find('\n') > -1 or text.find('\r') > -1 or text[0] == ' ' or
      text[-1] == ' '):
    text = '"%s"' % text
  return text