问题
I am basically trying to get Python to create a bunch of folders in a directory with each folders name based on a list in an Excel file. The list is in column D, that has a heading "Folder Name".
I have been able to do this with an individual cell, but struggling to figure out how to do it for multiple. The code I have so far is below.
Your help is really appreciated - I am very new to this!`
import os
import openpyxl
def folder_creation(EXCEL_FILE_DIRECTORY, FOLDER_CREATION_LOCATION, EXCEL_FILE_NAME):
os.chdir (EXCEL_FILE_DIRECTORY)
workbook = openpyxl.load_workbook (EXCEL_FILE_NAME)
sheet = workbook.get_sheet_by_name ('Sheet1')
folderName = sheet ['D2'].value
baseDir = FOLDER_CREATION_LOCATION
os.makedirs(os.path.join(baseDir, folderName))
print ("\nFolder created in: ", os.path.join(baseDir, folderName))
回答1:
You have to iterate through all column values. This works for me (openpyxl v2.5):
def folder_creation(EXCEL_FILE_DIRECTORY, FOLDER_CREATION_LOCATION, EXCEL_FILE_NAME):
os.chdir(EXCEL_FILE_DIRECTORY)
workbook = openpyxl.load_workbook(EXCEL_FILE_NAME)
sheet = workbook.get_sheet_by_name('Sheet1')
col_values = [cell.value for col in sheet.iter_cols(
min_row=2, max_row=None, min_col=4, max_col=4) for cell in col]
for value in col_values:
folderName = value
baseDir = FOLDER_CREATION_LOCATION
os.makedirs(os.path.join(baseDir, folderName))
print("\nFolder created in: ", os.path.join(baseDir, folderName))
回答2:
A for loop?
import os
import openpyxl
def folder_creation(EXCEL_FILE_DIRECTORY, FOLDER_CREATION_LOCATION, EXCEL_FILE_NAME):
os.chdir (EXCEL_FILE_DIRECTORY)
workbook = openpyxl.load_workbook (EXCEL_FILE_NAME)
sheet = workbook.get_sheet_by_name ('Sheet1')
baseDir = FOLDER_CREATION_LOCATION
col = sheet['D']
for cell in col:
folderName = cell.value
os.makedirs(os.path.join(baseDir, folderName))
print ("\nFolder created in: ", os.path.join(baseDir, folderName))
来源:https://stackoverflow.com/questions/50334591/python-create-multiple-folders-from-an-excel-column-list