Python: os、os.path使用

简单、快速了解Python类os、os.path的使用,了解获取当前路径,修改工作路径,删除文件,创建目录,获取文件一些基本信息等。

os

  • os.getcwd()

    ​ 获取当前路径

  • os.listdir()

    ​ 获取当前路径下所有项(文件、目录等)的列表,每一项为该项的路径

  • os.scandir(path='.')

    ​ 生成当前路径下所有项(文件、目录等)的迭代器,每一项为一个os.DirEntry,属性有 name、path、is_dir()、is_file()等

  • os.mkdir(path, mode=0o777, *, dir_fd=None)

    ​ 创建目录(非递归)

  • os.makedirs(name, mode=0o777, exist_ok=False)

    ​ 创建目录(递归)

  • os.chdir(path)

    ​ 修改工作路径

  • os.remove(path, *, dir_fd=None)

    ​ 删除文件

  • os.rmdir(path, *, dir_fd=None)

    ​ 删除目录,该目录必须为空

os.path

  • os.path.abspath(path)

    ​ 获取path的绝对路径

  • os.path.basename(path)

    ​ 获取路径的基本名称,即path末尾到最后一个斜杠的位置之间的字符串

  • os.path.dirname(path)

    ​ 获取路径的目录名称,即path开头到最后一个斜杠之前的字符串

  • os.path.join(path, *paths)

    ​ 拼接路径,注意:os.path.join(‘C:’, ‘file.txt’)返回C:file.txt,而不是C:\\file.txt,因为C:是磁盘符号

  • os.path.split(path)

    ​ 分割路径为dirname和basename,元组

  • os.path.splitext(path)

    ​ 分割路径为文件后缀符(前带.)和其他字符,元组,注意:os.path.splitext(’.csv’)返回(’.csv’, ‘’)

  • os.path.exists(path)

    ​ 判断路径是否存在

  • os.path.getatime(path)

    ​ 获取路径最后一次访问(access)的自纪元以来的秒数,浮点数

  • os.path.getmtime(path)

    ​ 获取路径最后一次修改(modify)的自纪元以来的秒数,浮点数

  • os.path.getctime(path)

    ​ 获取路径创建(create)的自纪元以来的秒数,浮点数

  • os.path.getsize(path)

    ​ 获取路径的大小(以byte为单位),路径应为文件,如果是目录得到的并准确

练习

1、树状显示路径下的所有目录、文件

import os
def treeView(path, prefix='-- '):
    """
    树状显示路径下的所有目录、文件
    
    Args:
    	path (str): 路径
    	prefix (str): 格式输出的字符
            
    Raises:
        FileNotFoundError: 路径不存在
    """
    # 判断路径是否存在,不存在抛出异常
    if not os.path.exists(path):
        raise FileNotFoundError('Path %s not exist!' % path)
    for it in os.scandir(path):
        print(prefix + it.name)
        # 判断it是否是目录,是目录则递归
        if os.path.isdir(it.path):
            treeView(it.path, '--' + prefix)

2、获取路径的大小

import os
def getSize(path):
    """
    获取路径的大小
    
    Args:
        path (str): 路径
    
    Return:
        size (int):路径大小(以byte为单位)
     
    Raises:
        FileNotFoundError: 路径不存在
    """
    # 判断路径是否存在,不存在抛出异常
    if not os.path.exists(path):
        raise FileNotFoundError('Path %s not exist!' % path)
        
    if os.path.isfile(path):
        return os.path.getsize(path)
    size = 0
    for it in os.scandir(path):
        # it是文件,直接加大小;it是目录,加递归大小
        if os.path.isfile(it.path):
            size += os.path.getsize(it.path)
        if os.path.isdir(it.path):
            size += getSize(it.path)
    return size
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值