Home > OS >  Python: How to makedirs from an excel file containing paths?
Python: How to makedirs from an excel file containing paths?

Time:10-03

How do I generate folders using the contents of my excel document?

I have been coding this for awhile and I just cannot seem to get it to work.

My objective is to create folders using an excel document which will include paths as displayed here; Excel spreadsheet contents

Excel document is named 'GreeceHoliday2018' and only contains 'Sheet1' located on my Desktop.

My intention was: Read the excel document -> read 'Sheet 1' -> print contents -> create a loop with contents to os.makedirs -> New folder (named 'Photos') with subfolders on desktop

import os
import pandas as pd
from openpyxl import load_workbook

os. chdir("C:\\Users\\NAME\\desktop")
workbook = pd.ExcelFile('GreeceHoliday2018.xlsx')
sheet = workbook.parse('Sheet1')

print (sheet)

os.getcwd()
path = os.getcwd()


print ("The current working Directory is %s" % path)

try:
        os.makedirs(sheet)

except OSError:
   print ("Creation of the directory %s failed" % path)
else:
  print ("Successfully created the directory %s " % path)

The following resulted in this:

Exception has occurred: TypeError: expected str, bytes or os.PathLike object, not DataFrame

Can anyone help me? I believe there must be a simple way to do this.

CodePudding user response:

Your returned sheet is a pandas Dataframe, that you can iterate over to extract the text from your sheet. You can then call os.makedirs() on each line of the text in your sheet, excluding the first line with the column name.

CodePudding user response:

Sheet is a DataFrame object that contains several attributes, try using sheet.values to get the values of the dataframe as a numpy array.

Read the docs to see all the attributes.

  • Related