How to convert a tab separated file to CSV format?

走远了吗. 提交于 2019-12-03 09:54:48

Import the data with excel (Data > Load from text file), using tab as a column separator. Then save the file as csv.

It cannot have compatibility issues, it's a basic task and i did it quite often in the past.

If you can use a scripting language, you might give Python a shot:

import csv

# read tab-delimited file
with open('yourfile.tsv','rb') as fin:
    cr = csv.reader(fin, delimiter='\t')
    filecontents = [line for line in cr]

# write comma-delimited file (comma is the default delimiter)
with open('yourfile.csv','wb') as fou:
    cw = csv.writer(fou, quotechar='', quoting=csv.QUOTE_NONE)
    cw.writerows(filecontents)

Example interpreter session:

>>> import csv
>>> with open('yourfile.tsv','rb') as fin:
...     cr = csv.reader(fin, delimiter='\t')
...     filecontents = [line for line in cr]
...
>>> with open('yourfile.csv','wb') as fou:
...     cw = csv.writer(fou, quotechar='', quoting=csv.QUOTE_NONE)
...     cw.writerows(filecontents)
...
>>> with open('yourfile.csv','rb') as see_how_it_turned_out:
...     for line in see_how_it_turned_out: 
...         line
... 
'attribute1,attribute2,attribute3,attributeN\r\n'
'value"A",value"B",value"C",value"Z"\r\n'

Notes:

Alternative line-terminator example:

with open('yourfile.csv','wb') as fou:
    cw = csv.writer(fou,quotechar='',quoting=csv.QUOTE_NONE,lineterminator='\n')
    ...

Here's some Excel-VBA code that will do this conversion. Paste this in Excel's visual basic editor (Alt-F11) and run it (after adjusting your filenames, of course).

Sub TabToCsv()

    Const ForReading = 1, ForWriting = 2
    Dim fso, MyTabFile, MyCsvFile, FileName
    Dim strFileContent as String
    Set fso = CreateObject("Scripting.FileSystemObject")

    ' Open the file for input.
    Set MyTabFile = fso.OpenTextFile("c:\testfile.dat", ForReading)

    ' Read the entire file and close.
    strFileContent = MyTabFile.ReadAll
    MyTabFile.Close

    ' Replace tabs with commas.
    strFileContent = Replace(expression:=strFileContent, _
                             Find:=vbTab, Replace:=",") 
    ' Can use Chr(9) instead of vbTab.

    ' Open a new file for output, write everything, and close.
    Set MyCsvFile = fso.OpenTextFile("c:\testfile.csv", ForWriting, True)
    MyCsvFile.Write strFileContent
    MyCsvFile.Close

End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!