2014-12-15 4 views
1

엑셀을 CSV로 변환해야합니다. 하지만 CSV 파일을 여러 개 작성할 수는 없습니다여러 csv 파일을 파이썬으로 작성하는 방법

import sys,os 

sys.path.insert(0,'D:/apera/Python27/xlrd-0.9.3') 

import xlrd 
import csv 

path = "D:/apera/Workspace/Sounding" 

CSVFile1 = "D:/apera/Workspace/Sounding/sounding001.csv" 
CSVFile2 = "D:/apera/Workspace/Sounding/sounding002.csv" 


for root,dirs,files in os.walk(path): 
    xlsfiles=[ _ for _ in files if _.endswith('.xls') ] 
    for xlsfile in xlsfiles: 
     wb = xlrd.open_workbook(os.path.join(root,xlsfile)) 
     n = len(wb.sheets()) 
     ws = wb.sheet_by_name("INPUT") 

     with open(CSVFile1, 'wb') as csvfile: 
      wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=';') 
      for rownum in xrange(ws.nrows): 
       wr.writerow(list(x.encode('latin1')for x in ws.row_values(rownum))) 

     with open(CSVFile2, 'wb') as csvfile: 
      wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=';') 
      for rownum in xrange(ws.nrows): 
       wr.writerow(list(x.encode('latin1')for x in ws.row_values(rownum))) 

     csvfile.close() 

편집 된 질문입니다. CSV 파일을 작성해야합니다. 이 파일은 2 개의 파일로 작성해야합니다. 그래서 나는 그것을 두 번 씁니다. 그래서 그것을 더 간단하게 만드는 방법이 있습니다. 그래서 열 필요가 없습니다 csvfile3, 4, 5 등등 .. 감사합니다

+0

사용 팬더를 ... pandas.ExcelFile' 객체 '로 읽은 다음'DataFrame.to_csv을 (사용)' csv에 쓸 함수. 훨씬 쉽게 말할 수 있습니다. –

+0

팬더 라이브러리인가요? – lalalala

+0

예 파이썬 윤활유 –

답변

2

"*"와일드 카드를 사용하여 여러 파일을 여는 방법에 대한 질문이 있다면, 당신은 glob 모듈을 사용할 수 있다고 생각합니다 (당신은 이미 언급 한 바와 같이) : 파이썬에서 파일 이름 와일드 카드에 대한

import glob 


file_names = glob.glob("*.txt") 

for file_name in file_names: 
    f = open(file_name, 'wb') 

    f.write("AAA") 

그리고 비슷한 질문이 이미 here을 논의했다.

0

당신은 (여러 CSV 파일에 기록)이 같은 작업을 수행 할 수 있습니다

import sys,os,xlrd,csv 

sys.path.insert(0,'D:/apera/Python27/xlrd-0.9.3') 

path = "D:/apera/Workspace/Sounding" 

files_to_write = ["D:/apera/Workspace/Sounding/sounding1.csv","D:/apera/Workspace/Sounding/sounding2.csv"] 

for root,dirs,files in os.walk(path): 
    xlsfiles=[ _ for _ in files if _.endswith('.xls') ] 
    for xlsfile in xlsfiles: 
     wb = xlrd.open_workbook(os.path.join(root,xlsfile)) 
     n = len(wb.sheets()) 
     ws = wb.sheet_by_name("INPUT") 
     for z in files_to_write:  
      with open(z, 'wb') as csvfile: 
       wr = csv.writer(csvfile, quoting=csv.QUOTE_ALL, delimiter=';') 
       for rownum in xrange(ws.nrows): 
        wr.writerow(list(x.encode('latin1')for x in ws.row_values(rownum)))  
+0

한 칸으로 들여 쓰기 하시겠습니까? 드문 일입니다. –

+0

번호 [네 칸을 사용하십시오.] (https://www.python.org/dev/peps/pep-0008/#indentation) –

+0

모든 CSV 파일을 가져 오는 것은 아닙니다. 내 폴더 내 모든 파일은 .xls에 있습니다. 그리고 나는 그들 모두를 csv 파일에 인쇄해야합니다. 따라서 코드에는 open (csvfile, 'wb')이 있습니다. 먼저 열어야 만 그는 그것을 쓸 수 있습니다. 그래서 다중으로 열고 쓰는 방법이 있습니까? – lalalala

관련 문제