How to create a directory in Python?

Asked

Viewed 15,940 times

12

How can I use Python to create a certain directory?

For example:

app/
   main.py

How could I create a directory called temp inside app through Python main.py?

  • Only two doubts, it would recursively temp folder cannot be "visible"?

  • @Guilhermenascimento I just need to create the directory :p

5 answers

12


Reply using Python 3.*

It is possible to use os.makedirs or os.mkdir.

os.makedirs

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

os.mkdir

Only creates the last directory. If the previous directories do not exist it will cause an error.
Ex.: os.mkdir('./temp/2016/12/09') - 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 cannot find the path specified: './1/2/3/4'


Example:

import os

dir = './temp'       
os.makedirs(dir)
# ou 
os.mkdir(dir)

9

There is more than one function for this:

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

The archive main.py is inside ./app then you can just use:

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

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

os.makedirs('./temp/2016/12/9')
  • 2

    Good! I was looking about the os.path.mkdir right now.

  • 1

    Incidentally, os.path.mkdir must be from Python 2

  • 1

    @jbueno is that I have not migrated pro 3, nor started to study. I have already edited, thank you!

  • All right, just for the record.

6

  • 1

    The idea of Lock seems great, it’s not the same subject, but I remembered a problem that occurred with a type of HD format, can occur to truncate the file during recording and a good way to avoid losses or conflicts would be to create a temporary and then move over each other, of course I do not know how to state behavior of a command cp tmp destino. I’ll read some more and refactor some codes :)

0

Although the previous answers are correct, from Python 3.4 give preference to the use of pathlib. In documentation and in the PEP 428 the reasons for.

Example: Little of the Functionality from os.path is reused. Many os.path functions are tied by Backwards Compatibility to confusing or Plain Wrong behaviour (for example, the Fact that os.path.abspath() simplifies ".." path Components without resolving symlinks first).

With pathlib, the solution to the question is as follows::

from pathlib import Path

Path('./temp').mkdir(exist_ok=True)

The exist_ok causes exceptions FileExistsError are ignored.

It is also possible to use the operator / to the Join directories. For example:

(Path('.') / 'temp' / 'subdir1' / 'sub2').mkdir(parents=True, exist_ok=True)

In this case it was necessary to add the option parents so that the entire directory chain could be created. Otherwise, the following error is launched: FileNotFoundError: [Errno 2] No such file or directory: 'temp/subdir1/sub2'

  • 1

    It would be interesting an example, to get a complete answer. The way it is I kind of "comment".

-4

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

import os

dirTemp = './temp'

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

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

  • 5

    If the directory already exists, what is the intention to remove it and create it again?

  • 1

    Besides having no sense in deleting a folder only to be able to create it, you still have the question that rmdir will fail if the folder contains any document or folder, issuing an exception OSError, error example in Windows: OSError: [WinError 145] A pasta não está vazia: '<nome da pasta>', or the script will end up there unless you treat "the error" with another try:. I recommend you rephrase the answer.

  • In what situation one might be interested in recreating a directory that already exists?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.