2017-02-03 193 views
2

我對python和Stackoverflow比較陌生,但希望任何人都可以解釋一下我當前的問題。我有一個python腳本,它從一個目錄中獲取excel文件(.xls和.xlsx),並將它們轉換爲.csv文件到另一個目錄。它在我的示例excel文件(包括4列和1行用於測試目的)上工作得很好,但是當我嘗試對具有excel文件的不同目錄(文件大小更大)運行我的腳本時,一個斷言錯誤。我附上我的代碼和錯誤。期待對這個問題有一些指導。謝謝!Python腳本讀取一個目錄中的多個excel文件,並將它們轉換爲另一個目錄中的.csv文件

import os 
import pandas as pd 

source = "C:/.../TestFolder" 
output = "C:/.../OutputCSV" 

dir_list = os.listdir(source) 

os.chdir(source) 

for i in range(len(dir_list)): 
    filename = dir_list[i] 
    book = pd.ExcelFile(filename) 

    #writing to csv 
    if filename.endswith('.xlsx') or filename.endswith('.xls'): 
     for i in range(len(book.sheet_names)): 
      df = pd.read_excel(book, book.sheet_names[i]) 

      os.chdir(output) 

      new_name = filename.split('.')[0] + str(book.sheet_names[i])+'.csv' 
      df.to_csv(new_name, index = False) 

     os.chdir(source) 

print "New files: ", os.listdir(output) 

The error message I receive when executing this script in the terminal shows as below:

+0

它看起來好像超過了允許的最大行數2 ** 14。文件有多大?或者它有多少行? –

+0

嗨塔拉斯,我目前在一個文件夾中有4個excel文件,其中一個文件大約有75k行。我可以使用另一個可以容納這樣一個大文件的軟件包嗎?謝謝。 – sujdrew

回答

0

由於您使用的是Windows,考慮噴氣/ ACE SQL引擎(Windows .dll文件)來查詢Excel工作簿和導出爲CSV文件,繞過需要加載/與大熊貓dataframes出口。

具體來說,使用pyodbc可使ODBC連接到Excel文件,遍歷每個工作表並使用SELECT * INTO ... SQL操作查詢導出到csv文件。 openpyxl模塊用於檢索表單名稱。下面的腳本不依賴相對路徑,因此可以從任何地方運行。假定每個Excel文件都有完整的標題列(在頂行的使用範圍內沒有丟失單元格)。

import os 
import pyodbc 
from openpyxl import load_workbook 

source = "C:/Path/To/TestFolder" 
output = "C:/Path/To/OutputCSV" 

dir_list = os.listdir(source) 

for xlfile in dir_list: 
    strfile = os.path.join(source, xlfile) 

    if strfile.endswith('.xlsx') or strfile.endswith('.xls'): 
     # CONNECT TO WORKBOOK 
     conn = pyodbc.connect(r'Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};' + \ 
           'DBQ={};'.format(strfile), autocommit=True) 
     # RETRIEVE WORKBOOK SHEETS 
     sheets = load_workbook(filename = strfile, use_iterators = True).get_sheet_names() 

     # ITERATIVELY EXPORT SHEETS TO CSV IN OUTPUT FOLDER 
     for s in sheets: 
      outfile = os.path.join(output, '{0}_{1}.csv'.format(xlfile.split('.')[0], s)) 
      if os.path.exists(outfile): os.remove(outfile) 

      strSQL = " SELECT * " + \ 
        " INTO [text;HDR=Yes;Database={0};CharacterSet=65001].[{1}]" + \ 
        " FROM [{2}$]"    
      conn.execute(strSQL.format(output, os.path.basename(outfile, s)) 
     conn.close() 

**注:此過程創建一個schema.ini文件,該文件在每次迭代串接。可以刪除。

相關問題