2016-09-14 78 views
-1

我需要幫助,我試圖爲電子表格中的每個項目(行)創建一個目錄,我如何使用python 3.5來完成此操作。 我嘗試使用pip和conda安裝熊貓,但它不工作,錯誤說我需要visual-C++ - 構建工具。即使安裝了這些工具,也會發生同樣的錯誤。 。 熊貓是在.xls工作表中爲每一行創建目錄的最佳方式嗎?我有多個.xls文件如何在.xls表單中爲每個項目創建一個目錄python

+1

您是否嘗試過使用內置的VBA? https://www.techonthenet.com/excel/formulas/mkdir.php –

回答

1

你的問題的一些觀點對我來說不是很清楚,但我會盡力爲你提供一些想法。 你可以使用xlrd(文檔在這裏:http://xlrd.readthedocs.io/en/latest/index.html)。

我們假設你有一個'sample.xls'文件,裏面有一些表格。對於每張表,您希望在'C:\ test'(讓我們假設它是Windows路徑)中創建多個文件夾作爲該表中的行數。假設您想要使用工作表名稱,然後使用累進號 來命名這些文件夾(您可以輕鬆編輯代碼以符合您的實際需要)。 PS:我同意使用CSV文件使事情變得更容易一些。

編輯:

下面的解決方案是基於您要創建多個文件夾中的XLS文件中的每個表(非空)細胞的數量的假設,並且每個文件夾有格式'sheetName_rowi_colj'的名稱' 其中i和j是兩個索引,它們與工作表中的單元格位置相關。

import os 
from xlrd import open_workbook 

parentPath = r"C:\test" 
xlsFile = open_workbook('sample.xls',ragged_rows=True) # Open the xls file 
for sheetName in xlsFile.sheet_names(): # Loop over the sheets inside the xls file 
    for rowIdx in range(xlsFile.sheet_by_name(sheetName).nrows): # Loop over the rows 
     for colIdx in range(xlsFile.sheet_by_name(sheetName).row_len(rowIdx)): # Loop over the columns for each row 
      if xlsFile.sheet_by_name(sheetName).cell_value(rowIdx,colIdx) != '': # Check if the cell is empty 
       childPath = ''.join([sheetName, '_row', str(rowIdx+1), '_col', str(colIdx+1)]) # +1 because indices start from zero 
       newPath = os.path.join(parentPath,childPath) 
       if not os.path.exists(newPath): # Make sure the path does not exist 
        os.makedirs(newPath) 

如果您有多個xls文件,只需循環它們即可。

0

如果將文件另存爲CSV,則此任務將更容易。試試這個:

import csv, sys, os 

folder_list = [] 
with open('folders.csv', 'rb') as f: 
    reader = csv.reader(f) 
    for row in reader: 
     for item in row: 
      if item != None: 
       folder_list.append(item) 
       print item 

for folder in folder_list: 
    try: 
     os.makedirs(folder) 
    except WindowsError as e: 
     pass 
相關問題