首页 > 解决方案 > 从 .xlsx 创建文件夹结构

问题描述

我有一个具有特定结构的 .xlsx 文件(请检查图像),我希望它通过 将包含的信息处理到特定的文件夹结构mkdir,我唯一拥有的是 .xlsx 和文件夹的名称是来自 .xlsx 前 3 个内容的字符串(也许我必须使用 VBA?):

在过程结束时,应该有 3 个新文件夹,里面有一张图片和 .txt 文件

这就是它最终的样子 -->工作流程和文件夹结构

应将 .png 的 URL 以及包含两个 ProdDec(生产说明)和 Collection 内容的单个 .txt 文件放入该创建的文件夹中。

我安装了 python 3.6.x 并且 PowerShell 也在我的 win7 64x 机器上。

非常感谢

雷纳·祖法尔

标签: python-3.xpowershell

解决方案


您可以使用openpyxl读取您的 Excel 文件,收集适当的信息,然后为每个产品创建一个目录。可以使用请求库下载图像。以下是针对您的问题的经过测试的解决方案:

import os

import openpyxl
import requests

wb = openpyxl.load_workbook('A1.xlsx')

sheet = wb.active

rows = [tuple(cell.value for cell in row if cell.value is not None) for row in sheet] # convert the cells to text

dirnames = list()
images = list()
text = list()

for row in rows[1:]: # [1:], ignore column headers for better looping
    if row[0] is not None:
        dirnames.append('_'.join(row[:3])) # joins the Brand, Family, and Ref columns
        images.append(row[3:-2]) # stores the uris in a tuple
        text.append('\r\n'.join(row[-2:])) # joins the last two columns

for i in range(len(dirnames)):
    if not(os.path.exists(dirnames[i])):
        os.mkdir(dirnames[i]) # create the dir
    os.chdir(dirnames[i]) # enter the dir
    print('creating', dirnames[i])
    for j, image in enumerate(images[i]): # for all of the images
        imagereq = requests.get(image)
        imagename = 'Img{}.png'.format(j + 1)
        if imagereq.status_code == 200: # prevents filewriting errors for bad requests
            with open(imagename, 'wb') as fp:
                fp.write(imagereq.content)
            print(' ' * 4 + 'image write successful for', imagename)
        else:
            print(' ' * 4 + 'could not download image {}, error'.format(imagename), imagereq.status_code, imagereq.reason)
    with open('ProdDesc_and_Collection.txt', 'wb') as fp:
        fp.write(text[i].encode('utf8'))

    os.chdir('..') # back out of the dir

更新:代码现在适用于每个产品的多个图像并忽略空单元格


推荐阅读