python-3.x - 从 .xlsx 创建文件夹结构
问题描述
我有一个具有特定结构的 .xlsx 文件(请检查图像),我希望它通过 将包含的信息处理到特定的文件夹结构mkdir
,我唯一拥有的是 .xlsx 和文件夹的名称是来自 .xlsx 前 3 个内容的字符串(也许我必须使用 VBA?):
在过程结束时,应该有 3 个新文件夹,里面有一张图片和 .txt 文件
这就是它最终的样子 -->工作流程和文件夹结构
应将 .png 的 URL 以及包含两个 ProdDec(生产说明)和 Collection 内容的单个 .txt 文件放入该创建的文件夹中。
我安装了 python 3.6.x 并且 PowerShell 也在我的 win7 64x 机器上。
非常感谢
雷纳·祖法尔
解决方案
您可以使用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
更新:代码现在适用于每个产品的多个图像并忽略空单元格
推荐阅读
- c# - 如何修复“DataTable”不包含 Microsoft Botframework v4 中“AsEnumerable”错误的定义?
- r - 为什么相同的 Google 搜索 API 在 R 和浏览器中产生不同的结果
- php - 会话开始后仍然显示登录页面
- python - 同一个csv中的多个工作表
- php - 类 App\Http\Request\CreatePost 不存在
- mysql - Angular 7:更新和删除功能不起作用
- office-js - 寻找“Outlook 加载项的保存功能”
- python - 如何改进我的代码以使其运行得更快?
- javascript - 如何设置我的文本在 3 秒后出现的超时时间?
- javascript - Angular8 和全日历组件