检查目录是否存在并在必要时创建它?
对此的直接答案是,假设您不希望其他用户或进程弄乱您的目录的简单情况:
if not os.path.exists(d):
os.makedirs(d)
或者,如果使目录受制于竞争条件(即,如果在检查路径存在之后,可能已经有其他东西),请执行以下操作:
import errno
try:
os.makedirs(d)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
但也许更好的方法是通过使用临时目录来回避资源争用问题tempfile
:
import tempfile
d = tempfile.mkdtemp()
以下是在线文档中的要点:
mkdtemp(suffix='', prefix='tmp', dir=None)
User-callable function to create and return a unique temporary
directory. The return value is the pathname of the directory.
The directory is readable, writable, and searchable only by the
creating user.
Caller is responsible for deleting the directory when done with it.
Python 3.5 中的新功能:pathlib.Path
使用exist_ok
有一个新Path
对象(从 3.4 开始)有很多方法可以用于路径 - 其中之一是mkdir
.
(对于上下文,我正在使用脚本跟踪我的每周代表。以下是脚本中代码的相关部分,可以让我避免每天针对相同的数据多次访问 Stack Overflow。)
首先是相关的进口:
from pathlib import Path
import tempfile
我们现在不必处理os.path.join
- 只需将路径部分加入/
:
directory = Path(tempfile.gettempdir()) / 'sodata'
然后我幂等地确保目录存在 -exist_ok
参数显示在 Python 3.5 中:
directory.mkdir(exist_ok=True)
这是文档的相关部分:
如果exist_ok
为真,FileExistsError
异常将被忽略(与命令的行为相同POSIX mkdir -p
),但前提是最后一个路径组件不是现有的非目录文件。
这是脚本的更多内容 - 就我而言,我不受竞争条件的影响,我只有一个进程希望目录(或包含的文件)在那里,并且我没有任何尝试删除的内容目录。
todays_file = directory / str(datetime.datetime.utcnow().date())
if todays_file.exists():
logger.info("todays_file exists: " + str(todays_file))
df = pd.read_json(str(todays_file))
Path
str
在其他期望str
路径的 API 可以使用它们之前,必须强制对象。
也许应该更新 Pandas 以接受抽象基类的实例,os.PathLike
.