How to create a directory in Python?

7

How can I use Python to create a particular directory?

For example:

app/
   main.py

How could you do to create a directory named temp within app through Python main.py ?

    
asked by anonymous 09.12.2016 / 14:11

4 answers

8

Answer using Python 3. *

You can use os.makedirs or < a href="https://docs.python.org/3/library/os.html#os.mkdir"> os.mkdir .

os.makedirs

Create all directories that are specified in the parameter, recursively. Eg: os.makedir('./temp/2016/12/09') will create the temp , 2016 , 12 and 09 folders.

os.mkdir

Only creates the last directory. If the previous directories do not exist it will cause an error.
For example: will only create the directory 09 and only if the previous ones exist, otherwise it will cause the following error

  

FileNotFoundError: [WinError 3] The system can not find the specified path: './1/2/3/4'

Example:

import os

dir = './temp'       
os.makedirs(dir)
# ou 
os.mkdir(dir)
    
09.12.2016 / 14:18
7

There is more than one function to this:

  • os.path.mkdir creates a folder ( os.mkdir if it's Python3)
  • os.makedirs creates folder (s) recursively

The file main.py is inside ./app so you can simply use:

os.path.mkdir('./temp') #Python 2
os.mkdir('./temp') #Python 3

If you want to create subfolders based on date (this helps to "navigate" faster later):

os.makedirs('./temp/2016/12/9')
    
09.12.2016 / 14:51
5

The most correct way to avoid race condition would be:

import os

try:
    os.makedirs("./temp")
except OSError:
    #faz o que acha que deve se não for possível criar
    
09.12.2016 / 14:20
-4

Eventually you may be interested in creating the './temp' folder even though it already exists in this case you can do this:

import os

dirTemp = './temp'

try:
    os.mkdir(dirTemp)
except OSError:
    os.rmdir(dirTemp)
    os.mkdir(dirTemp)

Avoid using 'dir' as a variable name because 'dir' is a Python function

    
02.05.2018 / 23:41