2011-04-08 6 views
16

이 형식의 텍스트 파일이 있습니다.탭으로 구분 된 파일을 CSV 형식으로 변환하는 방법

{ 

attribute1 attribute2 attribute3.... attributeN 

value"A" value"B" value"C".... value"Z" 

/* next line of values*/ 

} 

각 단어는 탭으로 구분됩니다.

CSV 형식으로 변환하려면 어떻게해야합니까? Excel을 사용해 보았지만 호환성 문제가 있습니다.

+0

CSV는 매우 정의 된 형식이 아닙니다. 어떤 것은 ";" 구분자로 ","를 사용하십시오. 날짜 서식도 매우 다양하며 문자열을 구분하는 옵션도 있습니다. 클라이언트 (사람 또는 프로세스)와 함께 이러한 요구 사항을 명확히해야합니다. –

답변

22

탭을 열 구분 기호로 사용하여 Excel에서 데이터를 가져옵니다 (데이터> 텍스트 파일에서로드). 그런 다음 파일을 csv로 저장하십시오.

호환성 문제가있을 수 없으며, 기본 작업이며 과거에 자주 수행했습니다.

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' 

주 : 당신이 scripting language를 사용할 수있는 경우

10

, 당신은 Python에게 기회를 줄 수도

  • default field delimiter,입니다. csv.writerdefault line terminator

  • \r\n,하지만 당신은 그래서 당신은 키워드 인수 AKA kwarg과 같은 대안을 지정할 수 있습니다 할 필요가있는 것이다.

대안 라인 종결 자 예 :

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

다음은이 변환을 할 몇 가지 엑셀 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 
+0

@jfc : 빈 줄과 {및 } –

+0

왜 OP가 필요한지에 달려 있습니다. 내 코드는 요청에 따라 "CSV 형식"으로 파일을 출력하지만 [ "CSV"는 실제로 한 가지만을 의미합니다] (http://en.wikipedia.org/wiki/ 쉼표로 구분 된 값) : 값은 쉼표 (일반적으로)와 줄 바꿈으로 구분됩니다 .OP에 수신자 응용 프로그램의'{'및'} '과 빈 줄이 필요한지 여부를 미리 판단 할 수 없습니다. OP가 모호하지 않은 예제 원하는 결과를 얻을 수 있다면 적절하게 답변 할 수있는 기회가 주어집니다. –

관련 문제