0

I'm trying to convert csv format to tsv. I just used this to change comma to tab.

tsv = re.sub(',', '\t', csv)

But I can't deal with the string with comma inside, for example:

dept_no,dt,hello
1,20180411,hello its me
2,20180412,here has tab
3,20180412,"here, is, commas"

Is there any way to convert to tsv without affecting comma inside of the string?

2

1 Answer 1

6

Try following, csv module should take care of inline commas.

import csv
csv.writer(file('output.tsv', 'w+'), delimiter='\t').writerows(csv.reader(open("input.csv"))) 

EDIT-1
[Added open method as per discussion]

Insted of using file where we are calling constructor directly, you can use open which is preferred way as per documentation here. Result is same.

csv.writer(open('output.tsv', 'w+'), delimiter='\t').writerows(csv.reader(open("input.csv")))

Result enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

file('output.tsv', 'w+') or open('output.tsv', 'w+') ?
Either is workable. open calls file internally as per documentation here : docs.python.org/2/library/functions.html#file. However open is preferred way by popularity.
Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.