python - 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,
解决方案
试试这个os.path.join
和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)
推荐阅读
- reactjs - 从 useEffect 之外的函数调用 API 数据的最佳实践是什么?
- ios - 如何在 WKWebView 中隐藏标记错误消息
- azure - 我在 grover gem 中面临以下问题: Grover::JavaScript::Error (net::ERR_NAME_NOT_RESOLVED) at
- python - 如何解决 python 虚拟环境中的 sqlite 依赖项?
- javascript - 如何将tensorflow js结果绘制到画布上?tf.browser.toPixels 的问题 - 仅显示旧结果
- curl - 请求获取 API 的所有可能的 API 端点
- json - 如何在 Apache Nifi 的末尾和开头删除 json 文件中的括号
- python - 使用 create_gantt() 创建甘特图时如何显示任务依赖关系?
- c# - 调整现有氧模型的大小
- python - OpenCV 颜色匹配