赞
踩
本文翻译自:mkdir -p functionality in Python [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
Is there a way to get functionality similar to mkdir -p
on the shell from within Python. 有没有办法在Python中从shell获得类似于mkdir -p
功能。 I am looking for a solution other than a system call. 我正在寻找除系统调用之外的解决方案。 I am sure the code is less than 20 lines, and I am wondering if someone has already written it? 我确信代码少于20行,我想知道是否有人写过它?
参考:https://stackoom.com/question/2W9k/Python中的mkdir-p功能-重复
In Python >=3.2, that's 在Python> = 3.2中,那就是
os.makedirs(path, exist_ok=True)
In earlier versions, use @tzot's answer . 在早期版本中,使用@ tzot的答案 。
- import os
- import tempfile
-
- path = tempfile.mktemp(dir=path)
- os.makedirs(path)
- os.rmdir(path)
As mentioned in the other solutions, we want to be able to hit the file system once while mimicking the behaviour of mkdir -p
. 正如其他解决方案中所提到的,我们希望能够在模仿mkdir -p
的行为的同时命中文件系统一次。 I don't think that this is possible to do, but we should get as close as possible. 我不认为这是可能的,但我们应该尽可能接近。
Code first, explanation later: 代码优先,稍后说明:
- import os
- import errno
-
- def mkdir_p(path):
- """ 'mkdir -p' in Python """
- try:
- os.makedirs(path)
- except OSError as exc: # Python >2.5
- if exc.errno == errno.EEXIST and os.path.isdir(path):
- pass
- else:
- raise
As the comments to @tzot's answer indicate there are problems with checking whether you can create a directory before you actually create it: you can't tell whether someone has changed the file system in the meantime. 由于对@ tzot的回答的注释表明在实际创建目录之前检查是否可以创建目录存在问题:在此期间您无法判断是否有人更改了文件系统。 That also fits in with Python's style of asking for forgiveness, not permission. 这也符合Python要求宽恕的风格,而不是许可。
So the first thing we should do is try to make the directory, then if it goes wrong, work out why. 所以我们要做的第一件事就是尝试制作目录,然后如果出错,找出原因。
As Jacob Gabrielson points out, one of the cases we must look for is the case where a file already exists where we are trying to put the directory. 正如Jacob Gabrielson指出的那样,我们必须寻找的案例之一就是我们试图放置目录的文件已经存在。
With mkdir -p
: 使用mkdir -p
:
- $ touch /tmp/foo
- $ mkdir -p /tmp/foo
- mkdir: cannot create directory '/tmp/foo': File exists
The analogous behaviour in Python would be to raise an exception. Python中的类似行为是引发异常。
So we have to work out if this was the case. 因此,如果是这种情况,我们必须解决。 Unfortunately, we can't. 不幸的是,我们做不到。 We get the same error message back from makedirs whether a directory exists (good) or a file exists preventing the creation of the directory (bad). 我们从makedirs获得相同的错误消息,无论目录是否存在(正常)还是存在防止创建目录(坏)的文件。
The only way to work out what happened is to inspect the file system again to see if there is a directory there. 找出问题的唯一方法是再次检查文件系统,看看那里是否有目录。 If there is, then return silently, otherwise raise the exception. 如果有,则以静默方式返回,否则引发异常。
The only problem is that the file system may be in a different state now than when makedirs was called. 唯一的问题是文件系统现在可能处于与调用makedirs时不同的状态。 eg: a file existed causing makedirs to fail, but now a directory is in its place. 例如:存在导致makedirs失败的文件,但现在一个目录就在其位置。 That doesn't really matter that much, because the the function will only exit silently without raising an exception when at the time of the last file system call the directory existed. 这并不重要,因为在最后一个文件系统调用目录时,该函数只会在不引发异常的情况下以静默方式退出。
Recently, I found this distutils.dir_util.mkpath : 最近,我发现了这个distutils.dir_util.mkpath :
- In [17]: from distutils.dir_util import mkpath
-
- In [18]: mkpath('./foo/bar')
- Out[18]: ['foo', 'foo/bar']
Function declaration; 功能声明;
- import os
- def mkdir_p(filename):
-
- try:
- folder=os.path.dirname(filename)
- if not os.path.exists(folder):
- os.makedirs(folder)
- return True
- except:
- return False
usage : 用法:
- filename = "./download/80c16ee665c8/upload/backup/mysql/2014-12-22/adclient_sql_2014-12-22-13-38.sql.gz"
-
- if (mkdir_p(filename):
- print "Created dir :%s" % (os.path.dirname(filename))
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。