我在这个格式的文本文件:如何将制表符分隔的文件转换为CSV格式?
{
attribute1 attribute2 attribute3.... attributeN
value"A" value"B" value"C".... value"Z"
/* next line of values*/
}
每个字由制表符分隔。
如何转换为CSV格式?我尝试使用Excel,但它给兼容性问题。
我在这个格式的文本文件:如何将制表符分隔的文件转换为CSV格式?
{
attribute1 attribute2 attribute3.... attributeN
value"A" value"B" value"C".... value"Z"
/* next line of values*/
}
每个字由制表符分隔。
如何转换为CSV格式?我尝试使用Excel,但它给兼容性问题。
用excel导入数据(数据>从文本文件加载),使用选项卡作为列分隔符。然后将该文件保存为csv。
它不具有兼容性问题,这是一项基本任务,我过去经常这样做。
如果你可以使用一个scripting language,你可能会给Python一个镜头:
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)
举例解释对话:
>>> 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'
注:
的default line terminator为csv.writer
是\r\n
,但你应该有需要的话可以指定一个替代作为关键字参数AKA kwarg。
替代线路终端器例如:
with open('yourfile.csv','wb') as fou:
cw = csv.writer(fou,quotechar='',quoting=csv.QUOTE_NONE,lineterminator='\n')
...
下面是一些Excel的VBA代码,会做这种转换。将其粘贴到Excel的可视化基本编辑器(Alt-F11
)中并运行它(当然,在调整文件名后)。
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
@jfc:它也应该删除空行和{ } – 2011-09-07 07:59:08
为什么?不一定。取决于OP的需求。我的代码按照要求输出一个“CSV格式”的文件,但[“CSV”真的意味着只有一个东西](http://en.wikipedia.org/wiki/)。逗号分隔值):值之间用逗号(通常)和换行符分开,我不能预先判断OP是否需要收件人应用程序中的'{'和'}'和空行。的期望输出,那么我们将有机会正确回答。 – 2011-09-07 08:19:18
请注意,CSV不是一个非常明确的格式。有些使用“;”作为分隔符,有些使用“,”。日期格式也是非常可变的,并且可以选择使用或不使用字符串来分隔字符串,您应该向客户(个人或流程)阐明这些要求 – 2011-09-07 08:02:36