ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

【python初级】 os.mkdir(path)创建目录

2021-12-04 13:59:14  阅读:245  来源: 互联网

标签:python 创建 mkdir directory path os 目录


【python初级】 os.mkdir创建目录

1、背景

创建目录,python可以使用os.mkdir(path)以及os.makedirs(path)。
其中os.makedirs(path)参考博客:
【python初级】 os.makedirs(path)递归的创建目录
https://jn10010537.blog.csdn.net/article/details/121684876

os.mkdir相比os.makedirs:
不同点:
os.mkdir不能递归的创建。即:如果目录有多级,则创建最后一级,
如果最后一级目录的上级目录有不存在的,则会抛出一个 OSError。比如:
在这里插入图片描述
相同点:
如果目录创建失败或者已经存在,会抛出一个 OSError 的异常,
Windows上Error 183 即为目录已经存在的异常错误,如下:
在这里插入图片描述
查看os.mkdir的描述:

import os
help(os.mkdir)

运行如下:

Help on built-in function mkdir in module nt:

mkdir(path, mode=511, *, dir_fd=None)
    Create a directory.
    
    If dir_fd is not None, it should be a file descriptor open to a directory,
      and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
      If it is unavailable, using it will raise a NotImplementedError.
    
    The mode argument is ignored on Windows.

参数
path – 要创建的目录,可以是相对或者绝对路径。
mode – 要为目录设置的权限数字模式。
返回值:没有返回值。

查看os.py中的 mkdir函数如下:

def mkdir(*args, **kwargs): # real signature unknown
    """
    Create a directory.
    
    If dir_fd is not None, it should be a file descriptor open to a directory,
      and path should be relative; path will then be relative to that directory.
    dir_fd may not be implemented on your platform.
      If it is unavailable, using it will raise a NotImplementedError.
    
    The mode argument is ignored on Windows.
    """
    pass

2、示例

os.mkdir(path, mode=511)创建目录:

import os
folder="./test1"
if not os.path.exists(folder):
    os.mkdir(folder)

解释:
判断folder目录是否存在,如果不存在则创建目录。

标签:python,创建,mkdir,directory,path,os,目录
来源: https://blog.csdn.net/jn10010537/article/details/121714713

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有