我需要一个简单的函数来在Python中创建一个路径,其中父路径可能存在也可能不存在。
根据python文档,如果父进程之一存在,os.makedirs将失败。
我已经编写了下面的方法,它的工作方式是根据需要创建尽可能多的子目录。
这看起来很有效吗?
def create_path(path):
import os.path as os_path
paths_to_create = []
while not os_path.lexists(path):
paths_to_create.insert(0, path)
head,tail = os_path.split(path)
if len(tail.strip())==0: # Just incase path ends with a / or \
path = head
head,tail = os_path.split(path)
path = head
for path in paths_to_create:
os.mkdir(path)
发布于 2014-01-25 19:15:19
下面是我的观点,它让系统库来处理所有的路径问题。除已存在的目录之外的任何错误都将被传播。
import os, errno
def ensure_dir(dirname):
"""
Ensure that a named directory exists; if it does not, attempt to create it.
"""
try:
os.makedirs(dirname)
except OSError, e:
if e.errno != errno.EEXIST:
raise
发布于 2011-08-11 03:30:17
草稿:
import os
class Path(str):
"""
A helper class that allows easy contactenation
of path components, creation of directory trees,
amongst other things.
"""
@property
def isdir(self):
return os.path.isdir(self)
@property
def isfile(self):
return os.path.isfile(self)
def exists(self):
exists = False
if self.isfile:
try:
f = open(self)
f.close()
exists = True
except IOError:
exists = False
else:
return self.isdir
return exists
def mktree(self, dirname):
"""Create a directory tree in this directory."""
newdir = self + dirname
if newdir.exists():
return newdir
path = dirname.split('/') or [dirname]
current_path = self + path.pop(0)
while True:
try:
os.mkdir(current_path)
except OSError as e:
if not e.args[0] == 17:
raise e
current_path = current_path + path.pop(0)
continue
if len(path) == 0:
break
return current_path
def up(self):
"""
Return a new Path object set a the parent
directory of the current instance.
"""
return Path('/'.join(self.split('/')[:-1]))
def __repr__(self):
return "<Path: {0}>".format(self)
def __add__(x, y):
return Path(x.rstrip('/') + '/' + y.lstrip('/'))
发布于 2012-11-02 02:46:58
尝试此代码,它检查路径是否存在,直到n个子目录级别,如果不存在,则创建目录。
def pathtodir(path):
if not os.path.exists(path):
l=[]
p = "/"
l = path.split("/")
i = 1
while i < len(l):
p = p + l[i] + "/"
i = i + 1
if not os.path.exists(p):
os.mkdir(p, 0755)
https://stackoverflow.com/questions/944536
复制相似问题