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?

Sophie.K
  • 15
  • 1
  • 5
  • 2
    Possible duplicate of [Read CSV file with comma within fields in Python](https://stackoverflow.com/questions/8311900/read-csv-file-with-comma-within-fields-in-python) – bkribbs Apr 13 '18 at 02:44
  • You should use the csv module to parse the file - it has this and other corner cases covered. – Paulo Scardine Apr 13 '18 at 02:50

1 Answers1

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

Anil_M
  • 10,893
  • 6
  • 47
  • 74