How to create a directory in Python?
How can I use Python to create a particular directory?
For example:
app/
main.py
How could I do to create a directory called temp
inside app
through Python main.py
?
5 answers
Answer using Python 3.*
Is it possible to use os.makedirs
or os.mkdir
.
os.makedirs
Creates all directories specified in the parameter, recursively.
Ex.: os.makedir('./temp/2016/12/09')
will create the folders temp, 2016, 12 e 09.
os.mkdir
Only creates the last directory. If the previous directories do not exist 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)
There is more than one function for this:
-
os.path.mkdir
creates a folder (os.mkdir
if it is Python3) -
os.makedirs
creates folder(s) recursively
The file main.py
is inside ./app
so you can just use:
os.path.mkdir('./temp') #Python 2
os.mkdir('./temp') #Python 3
If you want to create subfolders based on date (this helps to "browse" faster later):
os.makedirs('./temp/2016/12/9')
The most correct way to avoid running condition would be:
import os
try:
os.makedirs("./temp")
except OSError:
#faz o que acha que deve se não for possível criar
Although the previous answers are correct, as of Python 3.4 give preference to using pathlib. The reasons are explained in the documentation and in the PEP 428.
Example: Little of the functionality from os.path is reused. Many bones.path functions are tied by backwards compatibility to confusing or plain wrong behavior (for example, the fact that os.path.abspath () simplifies'.."path components without resolving symlinks first).
With pathlib, the solution to the question looks like this:
from pathlib import Path
Path('./temp').mkdir(exist_ok=True)
exist_ok
causes exceptions FileExistsError
to be ignored.
You can also use the /
operator for the join of 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 thrown:
FileNotFoundError: [Errno 2] No such file or directory: 'temp/subdir1/sub2'
Eventually you may be interested in creating from the folder'./ temp' even if it already exists in this case you can do like this:
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