0

I have a script that runs hourly.

The output folder structure should be /todaysdate/hour/

So, at 00:00, the script will run & it should create both the todaysdate folder and a subfolder called 00.

At 01:00, the script will run - the todaysdate directory exists, so it should only create the subdirectory.

I've tried the below, but that doesn't work - how would I approach this?

file_path = 'Desktop/%s/%s' %(today_date, hour)
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
    os.makedirs(directory)
ChaosPredictor
  • 2,885
  • 1
  • 24
  • 35
kikee1222
  • 1,184
  • 1
  • 9
  • 32

1 Answers1

1

You stated that you want to create directories for each hour. So you don't need to get the dirname. This should do it:

file_path = 'Desktop/%s/%s' %(today_date, hour)
if not os.path.exists(file_path):
    os.makedirs(file_path)

See docs for os.path.dirname. This gives you the directory that contains file_path, e.g.

file_path = "Desktop/22-10-2018/00"
print(os.path.dirname(file_path))
>>> "Desktop/22-10-2018/"
Bonlenfum
  • 16,095
  • 2
  • 45
  • 50
  • Also see the `exists_ok` flag, for python >3.2. https://stackoverflow.com/a/14364249/1643946. You can save yourself the os.path.exists test in this case – Bonlenfum Oct 22 '18 at 10:12