【发布时间】: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 似乎应该有更好的方法来做到这一点,所以我是否遗漏了什么,或者是唯一(或最好)的方法是我上面列出的算法?
谢谢。
【问题讨论】: