>>> import os
>>> os.path.isdir('/home')
True
>>> os.path.isdir('/usr/bin')
True
>>> os.path.isdir('/usr/bin/python')
False
# writing a single, non-recursive path
>>> if not os.path.exists('/home/cinnamon'):
... os.mkdir('/home/cinnamon')
# writing a single, recursive path
>>> if not os.path.exists('/home/alex/is/making/a/really/long/path'):
... os.makedirs('/home/alex/is/making/a/really/long/path')
# now to script the latter
>>> paths = ['/home/alex/path/one', ...]
>>> for path in paths:
>>> if not os.path.exists(path):
>>> os.makedirs(path)
我想你已经试过了,对吧?也许我误解了你的要求,但你说你想:
os.makedirs()
的文档以以下内容开头:你可以用os.path.exists模块。在
我会小心点,两者都用操作系统路径.isdir以及os.path.exists在尝试在目录内写入之前检查路径是否为目录,以及os.path.exists在覆盖路径之前。在
例如:
这样,您就不会覆盖任何存在的内容,在您写入目录之前,您需要检查某个目录是否是一个目录。根据设计,如果路径存在,系统会抛出一个OSError,因为它不知道您希望如何处理它。在
是否要覆盖路径(舒蒂尔.rmtree),是要存储路径已设置,还是跳过它?这是由你,编码者,来决定的。在
相关问题 更多 >
编程相关推荐