Common problem in CSV file writing

First let me tell you how I write CSV files :)
I don't use Pythons CSV module for writing. I just name the file xyz.csv (fp = open('xzy.csv', 'w')) and write using something like: fp.write(a+','+b+','+c)

But sometimes it can create a problem if any string contains a comma (,) within itself. For example if the string a is 'hello, how are you?', then it will be printed in two columns... so before writing to file I use:
a = a.replace(',', ' ')

Is there any other way to avoid such situation? If you know, please share.

Comments

astigmatik said…
Instead of replacing commas with spaces, why not escape them with a backslash "\"?
Paddy3118 said…
The writing part of the CSV module has some good ways to address this and other issues. You can either use the module, or re-implement parts of it as you too come across problems that the CSV module may have solutions to.

- Paddy.
aatiis said…
I must agree with paddy.
By the way, you could use e.g. '&c;' to replace commas, and '&a;' and '&s;' to replace '&' and ';'. Not very nice though...
aatiis said…
I've just posted a short review of your blog. Here's the link.
Tamim Shahriar said…
Thanks to all for your comments. I shall try your suggestions.
BTW, I found another way to get rid of the problem. Check the code:
name = '"'+item[0]+'"'
address = '"'+item[1]+'"'
phone = '"'+item[2]+'"'
fout.write(name+","+address+","+phone+"\n")

@aatiis, thanks for your review.

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code