AndrewSB
AndrewSB

Reputation: 951

Write volatile strings to file in Python

I have a lot of strings: about 14,000 in a list of tuples. alot of the strings have commas and newlines and maybe even unicode delimiters - not 100% sure.

I need to write the tuples to file, preferably in some format the excel or numbers can open. I tried CSV, but all the commas in the strings mess up the file.

How should I write my list of tuples to file, what format should the file be so that the weird content in the strings does not affect the formatting of the file

Upvotes: 0

Views: 305

Answers (3)

jmcnamara
jmcnamara

Reputation: 41604

If the target is Excel then you could use an Excel file writing module such as XlsxWriter or xlwt.

That would avoid any issues with CSV separators.

Upvotes: 1

abarnert
abarnert

Reputation: 365787

Don't change anything.

Since "my sample of tweets covers almost every unicode char", there is no reasonable safe delimiter you can choose.

But CSV has ways of dealing with that: escaping special characters, quoting fields with special characters in them, or both. There are many options to choose from, which you can see in Dialects and Formatting Parameters.

However, the default dialect is specifically designed to work well with Excel. And, since your goal is to put the data into some format that Excel can open, you can just use the defaults as-is. Unless you want to make it more readable and editable in a text editor, there is no problem.

Upvotes: 0

Aamir Rind
Aamir Rind

Reputation: 39659

In python csv module you can define the delimiter other than a comma:

csv.writer(file, delimiter=':')

Upvotes: 1

Related Questions