可能重复:
python中的mkdir -p功能
说我想制作一个文件:
filename = "/foo/bar/baz.txt"
with open(filename, "w") as f:
f.write("FOOBAR")
Run Code Online (Sandbox Code Playgroud)
这给了一个IOError,因为/foo/bar不存在.
什么是自动生成这些目录的最pythonic方式?难道真的要我明确调用os.path.exists并os.mkdir在每个单独的一个(即/富,则/富/条)?
Kru*_*lur 570
该os.makedirs功能可以做到这一点 请尝试以下方法:
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")
Run Code Online (Sandbox Code Playgroud)
添加try-except块的原因是处理os.path.exists在os.makedirs调用和调用之间创建目录的情况,以便保护我们免受竞争条件的影响.
在Python 3.2+中,有一种更优雅的方式可以避免上面的竞争条件:
filename = "/foo/bar/baz.txt"¨
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
249408 次 |
| 最近记录: |