python 创建嵌套列表_在Python中创建嵌套目录

python 创建嵌套列表

Creating multiple or nested directories in python should be implemented considering various error scenarios like,

应该考虑各种错误情况,例如在python中创建多个目录或嵌套目录

  1. Does the parent directory exist?

    父目录是否存在?

  2. What if the nested directories already exist?

    如果嵌套目录已经存在怎么办?

使用操作系统模块 (Using OS Module)

The most common module used in any file system operation is the os module. Using the os module, it is easy to work with the file system. Consider the below example which creates the nested directory which also evaluates the error scenario to ensure the code is not error or failure-prone.

在任何文件系统操作中最常用的模块是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)
>>>

The keyword exist_ok is an optional argument with default value as False. This keyword is only available in 3.2+. This keyword ensures that the exception is not raised if the directory already exists.

关键字exist_ok是一个可选参数,默认值为False 。 此关键字仅在3.2+中可用。 此关键字确保如果目录已经存在,则不会引发异常。

使用Pathlib模块 (Using Pathlib Module)

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)

In the above example, pathlib.Path.mkdir recursively creates the directory and does not raise an exception if the directory already exists.

在上面的示例中, pathlib.Path.mkdir递归创建目录,并且如果目录已经存在,则不会引发异常。

翻译自: https://www.includehelp.com/python/create-a-nested-directory.aspx

python 创建嵌套列表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值