我基本上试图让Python在一个目录中创建一堆文件夹,每个文件夹名称都基于Excel文件中的列表。该列表位于D列,其中包含标题"文件夹名称"。
我已经能够用一个单独的单元格做到这一点,但很难弄清楚如何做多个单元格。我到目前为止的代码如下。
非常感谢你的帮助 - 我对此很新!`
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))
答案 0 :(得分:1)
您必须遍历所有列值。这对我有用(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))
答案 1 :(得分:0)
for循环?
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))