Automatically creating directories with file output
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
mkdir -p functionality in python
假设我要制作一个文件:
1 2 3 4 | filename ="/foo/bar/baz.txt" with open(filename,"w") as f: f.write("FOOBAR") |
这给出了一个
自动生成这些目录最简单的方法是什么?对于我来说,是否有必要对每一个(即/foo,然后/foo/bar)明确地调用
1 2 3 4 5 6 7 8 9 10 11 12 13 | import os import errno filename ="/foo/bar/baz.txt" if not os.path.exists(os.path.dirname(filename)): try: os.makedirs(os.path.dirname(filename)) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise with open(filename,"w") as f: f.write("FOOBAR") |
添加
在python 3.2+中,有一种更优雅的方法可以避免上述竞争条件:
1 2 3 4 | filename ="/foo/bar/baz.txt"¨ os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename,"w") as f: f.write("FOOBAR") |