Blake Daniel
Blake Daniel

Reputation: 100

Python Formatting comma separated text string to save as csv file

I have comma separated text (string format) from as output from an API call, an small example shown below.

cs_file = 'Reviewer Name,Account Reviewer Name,Account Manager Name\r\n"Last, First","Last, First","Last, First"'

A new line is shown by '\r\n'. My thought would be to split the text at this first an then create a data frame by splitting at ",". However, splitting at '\r\n' does not work, just get one list...

cs_list = []

cs_list = cs_file.split(r'\r\n')

Any suggestions on a better approach? The goal would be to have this text saved as a csv.

Upvotes: 0

Views: 1533

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177554

The goal would be to have this text saved as a csv

The string is already in Excel CSV-file format, including proper quoting around fields that contain a delimiter and the newline format (\r\n). Write the string directly to a file specifying the newlines to be written without translation:

cs_file  = 'Reviewer Name,Account Reviewer Name,Account Manager Name\r\n"Last, First","Last, First","Last, First"'
with open('output.csv','w',newline='') as f:
    f.write(cs_file)

output.csv

Reviewer Name,Account Reviewer Name,Account Manager Name
"Last, First","Last, First","Last, First"

Note that newline='' is required in this case otherwise writing text on Windows translates \n to \r\n, resulting in \r\r\n when writing \r\n and then the CSV would display incorrectly if opened in Excel. See this question/answer for more explanation.

Upvotes: 1

HelixAchaos
HelixAchaos

Reputation: 131

You should use cs_list = cs_file.split('\r\n').

Using a raw-string would have worked if you assigned cs_file with cs_file = 'Reviewer Name,Account Reviewer Name,Account Manager Name\\r\\n"Last, First","Last, First","Last, First"'.

Python by default doesn't use raw-strings for assignment. I like to print strings to see how they visually look as all the escape characters can get confusing.

Upvotes: 1

Related Questions