Is there a Python method to create directories recursively? I have this path:
是否有Python方法递归创建目录?我有这条道路:
/home/dail/
I would like to create
我想创造
/home/dail/first/second/third
Can I do it recursively or I have to create one directory after the other?
我可以递归地执行此操作,还是必须在另一个目录之后创建一个目录?
The same thing for:
同样的事情:
chmod and chown can I do it recursively without assign permissions for each file/dir?
我可以递归地执行chmod和chown而不为每个文件/目录分配权限吗?
5 个解决方案
#1
157
os.makedirs
is what you need. For chmod
or chown
you'll have to use os.walk
and use it on every file/dir yourself.
os.makedirs是你需要的。对于chmod或chown,你必须使用os.walk并在你自己的每个文件/目录上使用它。
#2
58
a fresh answer to a very old question:
一个非常古老的问题的新答案:
starting from python 3.2 you can do this:
从python 3.2开始,你可以这样做:
import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)
thanks to the exist_ok
flag this will not even complain if the directory exists (depending on your needs....).
感谢exists_ok标志,如果目录存在,这甚至都不会抱怨(取决于你的需要......)。
starting from python 3.4 (which includes the pathlib module) you can do this:
从python 3.4(包括pathlib模块)开始,你可以这样做:
from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)
starting from python 3.5 mkdir
also has an exist_ok
flag - setting it to True
will raise no exception if the directory exists:
从python 3.5开始mkdir也有一个exist_ok标志 - 如果目录存在,将其设置为True将不会引发异常:
path.mkdir(parents=True, exist_ok=True)
#3
5
Here is my implementation for your reference:
以下是我的实现供您参考:
def _mkdir_recursive(self, path):
sub_path = os.path.dirname(path)
if not os.path.exists(sub_path):
self._mkdir_recursive(sub_path)
if not os.path.exists(path):
os.mkdir(path)
Hope this help!
希望这有帮助!
#4
4
I agree with Cat Plus Plus's answer. However, if you know this will only be used on Unix-like OSes, you can use external calls to the shell commands mkdir
, chmod
, and chown
. Make sure to pass extra flags to recursively affect directories:
我同意Cat Plus Plus的回答。但是,如果您知道这只会在类Unix操作系统上使用,则可以使用外部调用shell命令mkdir,chmod和chown。确保传递额外的标志以递归地影响目录:
>>> import subprocess
>>> subprocess.check_output(['mkdir', '-p', 'first/second/third'])
# Equivalent to running 'mkdir -p first/second/third' in a shell (which creates
# parent directories if they do not yet exist).
>>> subprocess.check_output(['chown', '-R', 'dail:users', 'first'])
# Recursively change owner to 'dail' and group to 'users' for 'first' and all of
# its subdirectories.
>>> subprocess.check_output(['chmod', '-R', 'g+w', 'first'])
# Add group write permissions to 'first' and all of its subdirectories.
EDIT I originally used commands
, which was a bad choice since it is deprecated and vulnerable to injection attacks. (For example, if a user gave input to create a directory called first/;rm -rf --no-preserve-root /;
, one could potentially delete all directories).
编辑我最初使用命令,这是一个糟糕的选择,因为它被弃用,容易受到注入攻击。 (例如,如果用户提供输入以创建名为first /; rm -rf --no-preserve-root /;的目录,则可能会删除所有目录)。
EDIT 2 If you are using Python less than 2.7, use check_call
instead of check_output
. See the subprocess
documentation for details.
编辑2如果您使用的Python小于2.7,请使用check_call而不是check_output。有关详细信息,请参阅子进程文档。
#5
1
Try using os.makedirs:
尝试使用os.makedirs:
import os
import errno
try:
os.makedirs(<path>)
except OSError as e:
if errno.EEXIST != e.errno:
raise
#1
157
os.makedirs
is what you need. For chmod
or chown
you'll have to use os.walk
and use it on every file/dir yourself.
os.makedirs是你需要的。对于chmod或chown,你必须使用os.walk并在你自己的每个文件/目录上使用它。
#2
58
a fresh answer to a very old question:
一个非常古老的问题的新答案:
starting from python 3.2 you can do this:
从python 3.2开始,你可以这样做:
import os
path = '/home/dail/first/second/third'
os.makedirs(path, exist_ok=True)
thanks to the exist_ok
flag this will not even complain if the directory exists (depending on your needs....).
感谢exists_ok标志,如果目录存在,这甚至都不会抱怨(取决于你的需要......)。
starting from python 3.4 (which includes the pathlib module) you can do this:
从python 3.4(包括pathlib模块)开始,你可以这样做:
from pathlib import Path
path = Path('/home/dail/first/second/third')
path.mkdir(parents=True)
starting from python 3.5 mkdir
also has an exist_ok
flag - setting it to True
will raise no exception if the directory exists:
从python 3.5开始mkdir也有一个exist_ok标志 - 如果目录存在,将其设置为True将不会引发异常:
path.mkdir(parents=True, exist_ok=True)
#3
5
Here is my implementation for your reference:
以下是我的实现供您参考:
def _mkdir_recursive(self, path):
sub_path = os.path.dirname(path)
if not os.path.exists(sub_path):
self._mkdir_recursive(sub_path)
if not os.path.exists(path):
os.mkdir(path)
Hope this help!
希望这有帮助!
#4
4
I agree with Cat Plus Plus's answer. However, if you know this will only be used on Unix-like OSes, you can use external calls to the shell commands mkdir
, chmod
, and chown
. Make sure to pass extra flags to recursively affect directories:
我同意Cat Plus Plus的回答。但是,如果您知道这只会在类Unix操作系统上使用,则可以使用外部调用shell命令mkdir,chmod和chown。确保传递额外的标志以递归地影响目录:
>>> import subprocess
>>> subprocess.check_output(['mkdir', '-p', 'first/second/third'])
# Equivalent to running 'mkdir -p first/second/third' in a shell (which creates
# parent directories if they do not yet exist).
>>> subprocess.check_output(['chown', '-R', 'dail:users', 'first'])
# Recursively change owner to 'dail' and group to 'users' for 'first' and all of
# its subdirectories.
>>> subprocess.check_output(['chmod', '-R', 'g+w', 'first'])
# Add group write permissions to 'first' and all of its subdirectories.
EDIT I originally used commands
, which was a bad choice since it is deprecated and vulnerable to injection attacks. (For example, if a user gave input to create a directory called first/;rm -rf --no-preserve-root /;
, one could potentially delete all directories).
编辑我最初使用命令,这是一个糟糕的选择,因为它被弃用,容易受到注入攻击。 (例如,如果用户提供输入以创建名为first /; rm -rf --no-preserve-root /;的目录,则可能会删除所有目录)。
EDIT 2 If you are using Python less than 2.7, use check_call
instead of check_output
. See the subprocess
documentation for details.
编辑2如果您使用的Python小于2.7,请使用check_call而不是check_output。有关详细信息,请参阅子进程文档。
#5
1
Try using os.makedirs:
尝试使用os.makedirs:
import os
import errno
try:
os.makedirs(<path>)
except OSError as e:
if errno.EEXIST != e.errno:
raise