2016-09-25 6 views
0

파이썬 2.7에서 현재 디렉토리의 모든 .xls 및 .xlsx 파일을 원래 파일 이름을 유지하면서 .csv로 변환하는 스크립트를 작성하려고합니다.Python : xls에서 csv로 여러 파일 변환

여기에 다른 유사한 질문에서 도움을

(슬프게도, 나는 빌린 코드의 조각 신용에 누구인지되지 않음), 여기에 내가 지금까지있어 무엇 :

import xlrd 
import csv 
import os 

def csv_from_excel(xlfile): 
    wb = xlrd.open_workbook(xlfile) 
    sh = wb.sheet_by_index(0) 
    your_csv_file = open(os.path.splitext(sxlfile)[0], 'wb') 
    wr = csv.writer(your_csv_file, dialect='excel', quoting=csv.QUOTE_ALL) 
    for rownum in xrange(sh.nrows): 
     wr.writerow(sh.row_values(rownum)) 
    your_csv_file.close() 

for file in os.listdir(os.getcwd()): 
     if file.lower().endswith(('.xls','.xlsx')): 
     csv_from_excel(file) 

나는 두 가지 질문이 있습니다

1) 프로그램을 실행할 때 한 파일 만 변환하고 현재 디렉토리의 모든 파일을 반복하지 않는 이유를 알아낼 수 없습니다.

2) 변환을 통해 원래 파일 이름을 유지하는 방법을 알 수 없습니다. 나는. 출력 파일이 입력과 이름이 같아야합니다.

답변

2

한 가지 가능한 솔루션 globpandas을 사용하는 것입니다 감사합니다.

excel_files = glob('*xls*') 

for excel in excel_files: 
    out = excel.split('.')[0]+'.csv' 
    df = pd.read_excel(excel, 'Sheet1') 
    df.to_csv(out)