在Python中递归创建目录

1 投票
1 回答
1580 浏览
提问于 2025-04-16 01:45

我需要用Python在这个目录下创建一个文件:

foo/bar/baz/filename.fil

问题是,我不知道baz、bar或者foo这些文件是否已经创建了(它们可能已经存在,但脚本并不能保证)。所以,显然我不能简单地这样做:

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

因为如果foo、bar或者baz不存在,我会遇到一个IO错误。所以,我在想我可以写一个脚本来

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应该有更好的方法来处理这个问题,那我是不是漏掉了什么,还是说唯一(或者最好的)方法就是我上面提到的算法呢?

谢谢。

1 个回答

4

使用 os.makedirs 这个函数。

撰写回答