【问题标题】:Making directories recursively in python [duplicate]在python中递归创建目录[重复]
【发布时间】:2011-03-20 07:47:30
【问题描述】:

我需要用python创建一个文件,在目录中:

foo/bar/baz/filename.fil

唯一的问题是我不知道是否已创建 baz、bar 甚至 foo(它们可能已创建,但脚本不能保证)。所以,显然我不能这样做:

file = open('foo/bar/baz/filename.fil', 'wb')
# Stuff
# file.close()

因为如果 foo 或 bar 或 baz 不存在,我会得到一个 IOError。所以,我在想我可以写一个脚本来

1.  Through a loop of os.path.split()s, get each directory.
2.  In a loop:  Test to see if each directory exists:
3.       If it doesn't: make it
4.  Then write the file.

但是,python 似乎应该有更好的方法来做到这一点,所以我是否遗漏了什么,或者是唯一(或最好)的方法是我上面列出的算法?

谢谢。

【问题讨论】:

    标签: python file


    【解决方案1】:

    使用os.makedirs

    【讨论】:

    • 啊,好吧...我错过了那个(正在查看 os.makedir),无论如何,尽管叶目录可能存在...尽管我猜这是一个简单的错误赶上。
    • @Leif:对。捕获 OSError 异常是最简单的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 2018-05-11
    • 2012-06-12
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多