Home > Software design >  How can create a nested directory?
How can create a nested directory?

Time:02-08

What is to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

import os

file_path = "/downloads/text.txt"
directory = os.path.dirname(file_path)

try:
    os.stat(directory)
except:
    os.mkdir(directory)

CodePudding user response:

Try this one for directory:

os.path.isdir(file_path)

To check if a file exist, try this:

os.path.isfile(file_path)

CodePudding user response:

The os.makedirs function creates all intermediate-level directories if they don't exist yet.

file_path = "downloads/test/text.txt"
directories = os.path.dirname(file_path)
os.makedirs(directories)
  •  Tags:  
  • Related