我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
我正在使用Python编写一个文件,我希望它被放置在一个特定的路径上。
也就是说:我如何检查文件夹是否存在,与其父母一起?如果路线上缺少文件夹,我如何创建它们?
当前回答
最快的安全方式是:如果不存在,它会创造,如果不存在,它会消失:
from pathlib import Path
Path("path/with/childs/.../").mkdir(parents=True, exist_ok=True)
其他回答
试试 os.path.exist 函数
if not os.path.exists(dir):
os.mkdir(dir)
如果你考虑下列事项:
os.path.isdir('/tmp/dirname')
这意味着一个目录(路径)存在,而且是一个目录,所以对我来说,这就是我所需要的,所以我可以确保它是文件夹(不是文件)并且存在。
我下载了下面的文章,但这不是完全愚蠢的。
import os
dirname = 'create/me'
try:
os.makedirs(dirname)
except OSError:
if os.path.exists(dirname):
# We are nearly safe
pass
else:
# There was an error on creation, so make sure we know about it
raise
如今,正如我所说的那样,这不是真正的愚蠢,因为我们有可能无法在那个时期创建目录,还有另一个创建过程。
我个人建议您使用 os.path.isdir() 测试而不是 os.path.exists()。
>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False
如果你有:
>>> directory = raw_input(":: ")
一个愚蠢的用户输入:
:: /tmp/dirname/filename.etc
... 您将以 filename.etc 命名的目录结束,当您将该论点转移到 os.makedirs(),如果您使用 os.path.exists()进行测试。
在Python中做到这一点的最佳方法
#Devil
import os
directory = "./out_dir/subdir1/subdir2"
if not os.path.exists(directory):
os.makedirs(directory)