首页 > 解决方案 > Creating new directories by iterating through specified dataframe values Python Pandas Numpy

问题描述

I am trying to create folders by reading each row from specific columns in a dataframe:

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: snapshot

df: snapshot

My current working directory: C:\Users\home\Desktop\test\

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

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

The new working directory is 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")

My output:

failed failed failed failed failed failed

I have over 400 rows in the raw df, I was just testing it for the first 6 rows.

What I am trying to achieve is as follows: End Result snapshot

so i am trying to take each row and using them to create a new directory, seperated by double underscores "__".

Additional note: I have deleted the folders from the working directory (the ones I created myself) and ran the code above and have still not attained the results I was after.

I Would have created a bash script, but that is not an options as I will need to populate these folders with various data such as images etc as I iterate through the dataframe.

any help would be greatly appreciated. I will continue to work on this and report back with a solution for everyones benefit if I am able to crack this.

Many Thanks,

标签: pythonpandasnumpydataframeoperating-system

解决方案


试试这个os.path.joinos.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)

推荐阅读