python学习Day-13

一、常用模块

1.os模块

# 1. os模块的作用
"""
os模块  -  文件或者文件夹(目录)或者路径相关操作
例如:创建文件夹、创建文件、删除文件、判断文件是否存在、获取绝路径、获取一个文件夹中所有的文件等等
"""
# 1)返回当前工作目录
print(os.getcwd())          # /Users/yuting/lessons/Python2201/01语言基础/day14-常用模块

# 2) 获取指定文件夹中所有的内容的名字
# os.listdir(文件夹路径)
result = os.listdir(r'/Users/yuting/Desktop/pdfs')
print(result)

# 3) 创建文件夹
"""
os.mkdir(文件夹路径)   -   在指定路径下创建指定的文件夹(整个路径中只有最后的那个文件夹不存在才可以创建)
os.makedirs(文件夹路径)  -  递归创建文件夹 (可以创建路径中所有不存在的文件夹)
"""
path = r'//aaa/files3'
# os.makedirs(path)

# 4)返回绝对路径
"""
os.path.abspath(相对路径)   -   返回相对路径对应的绝对路径

绝对路径:文件或者文件夹在计算机中全路径(windows电脑绝对路径从盘开始写)
相对路径:用.表示当前目录(当前目录指的是当前代码文件所在的文件夹)
         用..表示当前目录的上层目录

/Users/yuting/lessons/Python2201/01语言基础/day14-常用模块/demo.py
./demo.py
../day14-常用模块/demo.py
"""
print(os.path.abspath('./demo.py'))
print(os.path.abspath('/demo.py'))

# 5) 获取文件名
# os.path.basename(文件路径)   -   获取文件路径中的文件名
result = os.path.basename('//demo.py')
print(result)

# 6) 检测路径是否有效
print(os.path.exists('//demo.py'))

# 7) 判断是否是文件或者文件夹
"""
os.path.isfile(路径)  -  是否是文件
os.path.isdir(路径)   -   是否是文件夹
"""
count1 = count2 = 0
for x in os.listdir('./pdfs'):
    url = f'./pdfs/{x}'
    if os.path.isfile(url):
        count1 += 1
    elif os.path.isdir(url):
        count2 += 1
print(count1, count2)

# 8) 把目录和文件名合成一个路径
# os.path.join(文件夹路径, 文件名)
url = './files'
name = 'aaa.txt'
result1 = os.path.join(url, name)
result2 = f'{url}/{name}'
print(result1, result2)

# 9) 获取文件的扩展名(后缀)
url1 = './pdfs/学生信息2.csv'
result = os.path.splitext(url1)
print(result[-1])

2.math和random模块

# 1. 数学模块  -  math、cmath(针对复数的数学模块)
import math,  cmath
"""
1) 浮点数转整数
math.ceil(浮点数)      -      取较大整数
math.floor(浮点数)     -      取较小整数
round(浮点数)      -   四舍五入

2) 求绝对值
math.fabs(数字)   -  获取绝对值,结果是浮点数
abs(数据)  -  获取绝对值,结束的类型和指定数据的类型一样
"""
print(math.ceil(2.8799))    # 3
print(math.ceil(2.1001))    # 3
print(math.floor(2.8799))   # 2
print(math.floor(2.1001))   # 2
print(round(2.6799))        # 3
print(round(2.4001))        # 2

print(math.fabs(-29))       # 29.0
print(abs(-29))         # 29
print(abs(-23.56))      # 23.56

x = 10 + 2j
y = 20 - 3j
print(x + y)
print(x * y)

# 2. 随机模块 - random
"""
1)随机数
随机整数:random.randint(M, N)   -  产生M到N的随机整数
随机小数:random.random()   -  产生0到1的随机小数
random.randrange(M, N, step)   -  在指定的等差数列中随机获取一个数

2)洗牌
random.shuffle(序列)  -  洗牌(随机打乱序列中元素的顺序; 序列必须是可变的并且有序的)

3)抽牌
random.choice(序列)    -   从序列中随机获取一个元素
random.choices(序列, k=个数)   -  从序列中随机获取指定个数个元素(默认情况下元素的权重都一样;有放回抽取)
random.choices(序列, 权重值序列, k=个数)
random.sample(序列, k=个数)  -  从序列中随机获取指定个数个元素(无放回抽取)
random.sample(序列, k=个数, counts=权重序列)   -  Python3.9.0以后才可以使用
"""
import random

print(random.randint(10, 20))

# 0 ~ 1  -> 10 ~ 15
print(random.random(), random.random()*5 + 10)

print(random.randrange(10, 21, 2))

nums = [10, 20, 30, 40, 50, 60]
random.shuffle(nums)
print(nums)

result = random.choice('nums')
print(result)

result = random.choices(nums, k=2)
print(result)


options = ['特等奖', '一等奖', '二等奖', '三等奖', '再接再厉']
result = random.choices(options, [1, 3, 10, 100, 1000], k=1)
print(result)

nums = [10, 20, 30, 40, 50, 60]
result = random.sample(nums, k=2)
print(result)


options = ['特等奖', '一等奖', '二等奖', '三等奖', '再接再厉']
result = random.sample(options, k=3, counts=[1, 1, 1, 1, 1])
print(result)

options = ['特等奖', '一等奖', '二等奖', '三等奖', '再接再厉']
result = random.choices(options, [1, 1, 1, 1, 1], k=3)
print(result)

3.time模块

# 1. time.time()
"""
time.time()   -  获取当前时间,返回时间戳

时间戳  -  用指定时间到1970年1月1日0时0分0秒(格林威治时间)的时间差来表示一个时间,单位是秒

1646294602.6372879  -  '2022-3-3 04:10:39'
"""
t1 = time.time()        # 1646294602.6372879
print(t1)

# 2. time.localtime()
"""
time.localtime()   -  获取本地当前时间,返回结构体时间
time.localtime(时间戳)  -  将时间戳转换成本地时间对应的结构体时间
"""
t2 = time.localtime()
print(t2)

t3 = time.localtime(0)
print(t3)

t4 = time.localtime(1646294602.6372879)
print(t4, t4.tm_year)

# 3. time.mktime()
# time.mktime(结构体时间)   -  将结构体时间转换成时间戳
t5 = time.mktime(t4)
print(t5)       # 1646294602.0

# 4.time.strftime()
"""
time.strftime(时间格式字符串, 结构体时间)   -  将结构体时间转换成指定格式的字符串时间

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
"""
# xxxx年xx月xx日 xx:xx:xx
t_str1 = f'{t4.tm_year}年{t4.tm_mon}月{t4.tm_mday}日 {t4.tm_hour}:{t4.tm_min}:{t4.tm_sec}'
print(t_str1)

t_str2 = time.strftime('%Y年%m月%d日 %H:%M:%S', t4)
print(t_str2)

# xxxx/xx/xx
t_str3 = time.strftime('%Y/%m/%d', t4)
print(t_str3)

print(time.strftime('%B %A %p %I %H', t4))

# 5. time.strptime()
# time.strptime(字符串时间, 时间格式)   -  将字符串时间转换成结构体时间
t1 = '1992-3-4'
result = time.strptime(t1, '%Y-%m-%d')
print(f'周{result.tm_wday + 1}')

# 6. time.sleep()
# time.sleep(秒)   -  让程序暂停指定时间
time.sleep(3)
print('======================')

4.datetime模块

# 1. datetime类
# 1)获取当前时间
t1 = datetime.now()
print(t1, type(t1))

t2 = datetime.today()
print(t2)

# 2) 获取具体的时间信息
print(t1.year)
print(t1.month)
print(t1.day)
print(t1.hour)
print(t1.minute)
print(t1.second)
print(t1.weekday())

# 3) 字符串时间转datetime
# datetime.strptime(字符串时间, 时间格式)
result = datetime.strptime('2011年2月4日', '%Y年%m月%d日')
print(result, result.weekday())

# 4) 将datetime转化成字符串
# datetime时间对象.strftime(时间格式)
result = t1.strftime('%Y/%m/%d %a')
print(result)       # '2022/03/03 Thu'

# 5) 将datetime转换成结构体时间
# 时间对象.timetuple()
import time
result = t1.timetuple()
print(result)
print(time.mktime(result))

# 2.timedelta   -  完成时间的加减操作
# 注意:timedelta在完成时间加减操作的时候时间只能以秒、分、时、周或者天为单位
# 时间对象 +/- timedelta()
t2 = datetime.strptime('2022-12-31 23:59:40', '%Y-%m-%d %H:%M:%S')

# 1个小时以后的时间
result = t2 + timedelta(hours=1)
print(result)       # 2023-01-01 00:59:40

# 1个小时前的时间
result = t2 - timedelta(hours=1)
print(result)       # 2022-12-31 22:59:40

# 3天后
result = t2 + timedelta(days=3)
print(result)

# 1个小时30分钟前
result = t2 - timedelta(hours=1, minutes=30)
print(result)       # 2022-12-31 22:29:40

result = t2 - timedelta(weeks=3)
print(result)   # 2022-12-10 23:59:40

二、练习

import os.path
import shutil

while True:
    path_file =r"C:\Users\healing\Desktop\test"
    if os.path.exists(path_file):
        list1=os.listdir(path_file)
        for i in list1:
            path1=os.path.join(path_file,i)
            if os.path.isfile(path1):
                splitext=os.path.splitext(i)[1][1:]
                new_dir=os.path.join(path_file,splitext)
                new_path=os.path.join(path_file,splitext,i)
                if not os.path.exists(new_dir):
                    os.mkdir(new_dir)
                shutil.move(path1,new_path)
        else:
            print('整理完成!')
            break
    else:
        print('输入路径不存在,请重新输入!')
        continue

Python中,异常处理是非常重要的一部分。当程序运行时如果出现错误,如果没有异常处理,程序就会崩溃。为了避免这种情况,Python提供了异常处理机制。 在Python中,异常处理语句使用 `try` 和 `except` 关键字来实现。`try` 语句块中包含可能会发生异常的代码,如果这段代码出现了异常,则会跳转到 `except` 语句块中执行异常处理代码。 下面是一个简单的例子: ```python try: num = int(input("请输入一个整数:")) print(10/num) except ZeroDivisionError: print("除数不能为0") except ValueError: print("输入的不是整数") ``` 在上面的代码中,我们尝试将用户输入的字符串转换为整数,并将其用作除数计算 10/num。如果用户输入的是 0,则会触发 ZeroDivisionError 异常。如果用户输入的不是整数,则会触发 ValueError 异常。如果发生异常,则会跳转到对应的 except 语句块中执行处理代码。 除了可以指定具体的异常类型,也可以使用 `except Exception` 来捕获所有异常。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) ``` 在上面的代码中,如果发生任何异常,都会跳转到 `except` 语句块中执行处理代码,并将异常信息打印出来。 除了 `try` 和 `except`,还有 `finally` 关键字,它指定的代码块无论是否发生异常都会执行。例如: ```python try: num = int(input("请输入一个整数:")) print(10/num) except Exception as e: print("发生异常:", e) finally: print("程序执行完毕") ``` 在上面的代码中,无论是否发生异常,都会执行 `finally` 中的代码,即输出“程序执行完毕”。 总之,在Python中,异常处理是非常重要的一部分,它可以有效避免程序崩溃,提高程序的健壮性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值