通过迭代指定的数据帧值来创建新目录 Python Pandas Numpy

我正在尝试通过从数据框中的特定列读取每一行来创建文件夹:


import numpy as np

import pandas as pd

import os


raw_df = pd.read_excel('C:/Users/home/Desktop/test/Inventory.xls')

df = raw_df[["Barcode", "Brand", "product_name"]]

raw_df:快照


df:快照


我当前的工作目录:C:\Users\home\Desktop\test\


path = os.getcwd()

new_path = os.chdir(path + "\\products\\")


print ("The new working directory is %s" % os.getcwd())

新的工作目录是 C:\Users\home\Desktop\test\products\


for i in range(len(df)):

    row = df.iloc[i]

    barcode = row["Barcode"]

    brand = row["Brand"]

    product_name = row["Product_Name"]

    if(("\\" + barcode + "\\__" + brand + "\\__" + product_name + "\\") == False):

        os.makedir("\\" + barcode + "\\__" + brand + "\\__" + product_name + "\\")

    else:

        print("failed")

我的输出:


失败失败失败失败失败失败失败


我在原始 df 中有超过 400 行,我只是在测试前 6 行。


我想要实现的目标如下:最终结果快照

http://img4.mukewang.com/61a5e649000186bc04570182.jpg

所以我试图获取每一行并使用它们创建一个新目录,由双下划线“__”分隔。


附加说明:我已经从工作目录(我自己创建的文件夹)中删除了文件夹并运行了上面的代码,但仍然没有达到我想要的结果。


我会创建一个 bash 脚本,但这不是一个选项,因为在我遍历数据帧时,我需要用各种数据(例如图像等)填充这些文件夹。


任何帮助将不胜感激。如果我能够破解这个问题,我将继续为此工作,并为每个人的利益报告一个解决方案。


Smart猫小萌
浏览 167回答 2
2回答

慕田峪4524236

用os.path.joinand试试这个os.path.isdir:for i in range(len(df)):    row = df.iloc[i]    barcode = row["Barcode"]    brand = row["Brand"]    product_name = row["Product_Name"]    mypath = os.path.join(new_path, barcode, "__" + brand, "__" + product_name)    if (os.path.isdir(mypath)):        print("failed")    else:        os.mkdir(mypath)

茅侃侃

感谢您的帮助并为我指明正确的方向,我设法使以下代码正常工作:for i in range(len(df)):&nbsp; &nbsp; row = df.iloc[i]&nbsp; &nbsp; barcode = row["Barcode"]&nbsp; &nbsp; brand = row["Brand"]&nbsp; &nbsp; product_name = row["Product_Name"]&nbsp; &nbsp; mypath = os.getcwd() + "\\" + barcode + "__" + brand + "__" + product_name + "\\"&nbsp; &nbsp; if(os.path.isdir(path) == False):&nbsp; &nbsp; &nbsp; &nbsp; os.mkdir(path)&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("failed")正如@vercelli 所提到的,确保您的数据框不包含其字段中的任何值:/:*?"<>|由于这些是用于创建目录的无效字符,我对其他系统不太熟悉,但 windows 肯定不接受这些字符来创建具有这些值的目录。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python