Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is different between makedirs and mkdir of os?

I am confused to use about these two osmethods to create the new directory.

Please give me some example in Python.

like image 840
Toni Avatar asked Dec 11 '12 11:12

Toni


People also ask

What is Makedirs?

The os. makedirs() method is used to create a directory recursively in the os module using Python. It is similar to the method os. mkdir() with the addition that it also creates intermediate directories to create leaf directories.

What is the use of mkdir () and Mkdirs () methods in Python?

Creating a directory is a common operation in Python when you're working with files. The os. mkdir() method can be used to create a single directory, and the os. makedirs() method can be used to create multi-level directories.

What is mode in os mkdir?

os.mkdir(path[,mode]) path is the path where you want to complete the new directory. mode is the mode of the directory to be given. The default mode is 0777 ( o c t a l ) 0777 (octal) 0777(octal).

Does os mkdir create subdirectories?

With the os module, if you want to create just a single directory, you can use os. mkdir() (make directory) with the directory name, which creates a single subdirectory with the given name.


1 Answers

makedirs() creates all the intermediate directories if they don't exist (just like mkdir -p in bash).

mkdir() can create a single sub-directory, and will throw an exception if intermediate directories that don't exist are specified.

Either can be used to create a single 'leaf' directory (dirA):

  • os.mkdir('dirA')
  • os.makedirs('dirA')

But makedirs must be used to create 'branches':

  • os.makedirs('dirA/dirB') will work [the entire structure is created]

mkdir can work here if dirA already exists, but if it doesn't an error will be thrown.

Note that unlike mkdir -p in bash, either will fail if the leaf already exists.

like image 59
NPE Avatar answered Sep 20 '22 17:09

NPE