11

I want to check if a folder by the name "Output Folder" exists at the path

D:\LaptopData\ISIS project\test\d0_63_b4_01_18_ba\00_17_41_41_00_0e

if the folder by the name "Output Folder" does not exist then create that folder there.

can anyone please help with providing a solution for this?

Ankit
  • 129
  • 1
  • 1
  • 5
  • You can use `os.path.exists('')` to check folder exists or not. – stud3nt Dec 26 '19 at 11:24
  • 2
    Does this answer your question? [How do I check whether a file exists without exceptions?](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions) – Emily Dec 26 '19 at 11:26
  • 1
    Does this answer your question? [How can I safely create a nested directory?](https://stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory) – Manthan Tilva Dec 26 '19 at 11:42

6 Answers6

23

The best way would be to use os.makedirs like,

os.makedirs(name, mode=0o777, exist_ok=False)

Recursive directory creation function. Like mkdir(), but makes a intermediate-level directories needed to contain the leaf directory.

The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed.

>>> import os
>>> os.makedirs(path, exist_ok=True) 
# which will not raise an error if the `path` already exists and it
# will recursively create the paths, if the preceding path doesn't exist

or if you are on python3, using pathlib like,

Path.mkdir(mode=0o777, parents=False, exist_ok=False)

Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raises FileNotFoundError. > If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.

Changed in version 3.5: The exist_ok parameter was added.

>>> import pathlib
>>> path = pathlib.Path(somepath)
>>> path.mkdir(parents=True, exist_ok=True)
han solo
  • 5,018
  • 1
  • 7
  • 15
5
import os
import os.path

folder = "abc"
os.chdir(".")
print("current dir is: %s" % (os.getcwd()))

if os.path.isdir(folder):
    print("Exists")
else:
    print("Doesn't exists")
    os.mkdir(folder)

I hope this helps

Kaustubh.P.N
  • 129
  • 6
2
  • Search for folder whether it exists or not, it will return true or false:
    os.path.exists('<folder-path>')
  • Create a new folder: os.mkdir('<folder-path>')

Note: import os will be required to import the module.

Hope you can write the logic using above two functions as per your requirement.

stud3nt
  • 1,792
  • 1
  • 8
  • 19
2

pathlib application where csv files need to be created inside a csv folder under parent directory, from a xlsx file with full path (e.g., taken with Path Copy Copy) provided.
If exist_ok is true, FileExistsError exceptions will be ignored, if directory is already created.

from pathlib import Path

wrkfl = 'C:/xlsx/my.xlsx'  # path get from Path Copy Copy context menu
xls_file = Path(wrkfl)
(xls_file.parent / 'csv').mkdir(parents=True, exist_ok=True) 
1
import os


def folder_creat(name, directory):
    os.chdir(directory)
    fileli = os.listdir()
    if name in fileli:
        print(f'Folder "{name}" exist!')
    else:
        os.mkdir(name)
        print(f'Folder "{name}" succesfully created!')
        return


folder_creat('Output Folder', r'D:\LaptopData\ISIS project\test\d0_63_b4_01_18_ba\00_17_41_41_00_0e')
Kevin Omar
  • 123
  • 9
1

This piece of code does the exactly what you wanted. First gets the absolute path, then joins folder wanted in the path, and finally creates it if it is not exists.

import os

# Gets current working directory
path = os.getcwd()

# Joins the folder that we wanted to create
folder_name = 'output'
path = os.path.join(path, folder_name) 

# Creates the folder, and checks if it is created or not.
os.makedirs(path, exist_ok=True)