Python学习笔记4:回顾

回顾

手动抛出异常

raise 异常名称(’输出的提示信息’)

raise NameError('我出错了')

Traceback (most recent call last):
  File "F:/qianfeng/python36/day08/1手动抛出异常.py", line 1, in <module>
    raise NameError('我出错了')
NameError: 我出错了

一 装饰器

def demo(x):
    def inner(age):
        if age <= 10:
            myStr = '儿童'
        elif age <= 20:
            myStr = '青年'
        else:
            myStr = '老年人'
        x(myStr)
    return inner

@demo  # 等价于 func = demo(func)
def func(people):
    print('你现在已经步入了{}阶段'.format(people))

func(30)  # 你现在已经步入了老年人阶段

二 os模块

如果想使用os模块,那么你需要先导入os模块

import os

        函数名                              函数的说明                  
      os.name           获取当前操作系统的类型(nt-windows, posix-Linux, Unix)
     os.environ                          获取环境变量                 

os.environ.get(‘path’) 获取某一个的环境变量
os.curdir 获取当前目录
os.getcwd() 获取当前工作目录的绝对路径
os.listdir() 以列表的形式返回当前工作目录下的所有文件名
os.mkdir() 创建目录
os.rmdir() 删除文件夹
os.rename(dir1, dir2) 将dir1重命名为dir2
os.path.join(path, file) 拼接路径
os.path.splitext() 获取文件扩展名
os.path.isdir() 判断是否是目录
od.path.isfile() 判断是否是文件
os.path.exists() 判断文件或目录是否存在
os.path.getsize() 获取文件的大小,返回字节数
os.path.dirname() 获取目录名
os.path.basename() 获取文件名
os.path.abspath() 获取一个文件的绝对路径
os.path.split() 拆分路径和文件名

利用递归统计文件信息:

# 递归遍历目录,统计目录大小,并以列表的形式返回所有py文件

import os
path = 'F:/qianfeng/python36/day08/nian'
dicList = []

def myTotalSize(path):
    # 全局变量dicList,存放py文件名
    global dicList

    # 存放目录字节数
    memory = 0

    # 当前目录下的文件列表
    fileList = os.listdir(path)

    for file in fileList:  # 以列表的形式返回该目录下的所有文件
        # print(file)
        newPath = os.path.join(path, file)  # 将每一个文件拼接成绝对路径
        # print(newPath)

        # 判断是否为目录
        if os.path.isdir(newPath):
            memory += myTotalSize(newPath)  # 累加每个目录的大小

        # 判断是否为文件
        elif os.path.isfile(newPath):
            # 判断是否为py文件
            if os.path.splitext(newPath)[1].upper() == '.PY':
                dicList.append(os.path.basename(newPath))
            memory += os.path.getsize(newPath)  # 累加每个文件的大小

    # 返回文件大小
    return memory


# 打印目录大小(总字节数)
print(myTotalSize(path))

# 打印py文件列表
print(dicList)

利用堆栈来获取目录下所有文件名:

import os
path = 'F:/qianfeng/python36/day08/nian'

myList = []
myList.append(path)


while len(myList) != 0:
    myPath = myList.pop()
    # print(myPath)
    # 返回当前目录下的所有文件
    myListDir = os.listdir(myPath)

    for fileName in myListDir:
        # print(fileName)
        newPath = os.path.join(path, fileName)  # 拼凑一个新的完整路径
        if os.path.isdir(newPath):
            myList.append(newPath)
        else:
            print('文件名:', fileName)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值