应该考虑各种错误情况,例如在python中创建多个或嵌套目录,
父目录是否存在?
如果嵌套目录已经存在怎么办?
在任何文件系统操作中最常用的模块是os模块。使用os模块,可以很容易地使用文件系统。考虑下面的示例,该示例创建嵌套目录,该目录还评估错误情况以确保代码不出错或不易出错。
-bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> directory_to_be_created = 'test/include/help' >>> os.makedirs(directory_to_be_created, exist_ok=True) >>>
关键字exist_ok是一个可选参数,默认值为False。此关键字仅在3.2+中可用。此关键字确保如果目录已经存在,则不会引发异常。
Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import pathlib >>> pathlib.Path('test_1/directory').mkdir(parents=True, exist_ok=True)
在上面的示例中,pathlib.Path.mkdir递归创建目录,并且如果目录已经存在,则不会引发异常。