第十六天 常用系统模块

1. os模块 - 用来提供文件和文件夹相关操作的模块

import os

1) os.getcwd() - 获取当前目录

print(os.getcwd()) # ‘/Users/yuting/lessons/Python2107/01语言基础/day16-常用系统模块’
open(os.getcwd() + ‘/test.py’)

2) os.listdir(文件夹路径) - 获取指定文件夹下所有的文件和文件夹的名字(获取指定文件夹下所有的内容)

# 练习:读取files文件夹中所有的文件内容
print(os.listdir('./files'))      # ['file2.txt', 'file1.txt', 'file4.html', 'file3.c']
for file_name in os.listdir('./files'):
    result = open('./files/'+file_name).read()
    print(result)

# 练习:读取files中所有txt文件的文件内容
 for file_name in os.listdir('./files'):
     if file_name[-4:] == '.txt':
         result = open('./files/'+file_name).read()
         print(result)

3) 创建文件夹 - mkdir、makedirs

# os.mkdir('./files/a')
# os.makedirs('./files/aaa/bbb/ccc')

4) os.path.basename(文件路径) - 返回文件名

result = os.path.basename(’./files/file1.txt’)
print(result)

5) os.path.exists(文件/文件夹路径) - 判断指定文件或者文件夹是否存在


result = os.path.exists('./files/file1.txt')
print(result)       # True

result = os.path.exists('./files/file11.txt')
print(result)       # False

6) os.path.splitext(文件路径) - 文件名和后缀分离

print(os.path.splitext(‘files/file1.txt’))

1. 数学模块

import math         # 这里面所有的工具都是针对普通数字的
import cmath        # 这里面所有的工具都是针对复数的

Python中和数字相关的类型有4中:int、float、bool、complex

ai + b - 复数, i叫虚数单位,i**2 == -1

注意: python中的复数,j是虚数单位

x = 3 + 2j
y = -4 + 3j
print(x + y)        # (-1+5j)
print(x * y)        # (-18+1j)

math 模块

1) 小数转整数

# math.ceil(数字)     -  向大取整
# math.floor(数字)    -  向小取整
# round(数字)   -     四舍五入
print(math.ceil(1.9))       # 2
print(math.ceil(1.1))       # 2
print(math.floor(1.9))      # 1
print(math.floor(1.1))      # 1
print(round(1.9))           # 2
print(round(1.1))           # 1
# print(math.degrees(3.1415926))     圆周率

2)求绝对值

# abs(数字)
# math.fabs(数字)
print(abs(-30))     # 30
print(math.fabs(-30))   # 30.0

print(abs(-30.56))      # 30.56
print(math.fabs(-30.56))   # 30.56

2.随机模块

import random

1) 产生随机整数: random.randint(a,b) - 产生a到b的随机整数, [a, b]

print(random.randint(1, 2))

2) 产生随机小数:random.random() - 产生0~1的随机小数

print(random.random())

# 产生0~100的随机小数
print(random.random() * 100)

# 产生50~100的随机小数
print(random.random() * 50 + 50)

产生M~N的随机小数:random.random() * (N-M) + M

3)在指定的等差数列中随机获取一个数: random.randrange(起点, 终点, 步长) - [起点, 终点)

# 产生0~100的随机偶数
print(random.randrange(0, 101, 2))

4) 洗牌(随机打乱列表中元素的顺序)

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

5) 抽牌

# random.choice(序列)    -   随机获取一个元素
# random.choices(序列, k=数量, cum_weights=权重值)  -   随机获取多个元素(有放回)
# random.sample(序列, k=数量)   -   随机获取多个元素(无放回)
nums = ['宝马M5', '清空购物车', '现金200万', '谢谢!']
result = random.choices(nums, cum_weights=[1, 3, 1, 10000], k=3)
print(result)

result = random.sample(nums, k=3)
print(result)

import time

补充:时间戳
“”"
时间戳指的是某一个时间到1970年1月1日0时0分0秒(格林威治时间)的时间差,单位是秒
1639986631.790727
‘2021年12月20日 15:55:00’
“”"

1. time.time() - 获取当前时间(当前时间的时间戳)

t1 = time.time()
print(t1, type(t1))       # 1639986631.790727   <class 'float'>

2. time.localtime()

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

通过结构体时间单独获取指定信息

tm_wday - 星期值,从06表示是周一周天

print(t2.tm_year, t2.tm_mon)

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

t4 = time.localtime(1639986631.790727)
print(t4)

3. time.sleep(时间) - 让程序暂停/等待指定时间(单位秒)

# time.sleep(2)
# print('===============')

结构体时间和字符串时间的相互转换

xxxx-xx-xx xx:xx:xx

xxxx/xx/xx xx:xx:xx

xxxx年xx月xx日 xx时xx分xx秒

python中时间日期格式化符号:
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身

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

print(t2)   # time.struct_time(tm_year=2021, tm_mon=12, tm_mday=20, tm_hour=16, tm_min=28, tm_sec=20, tm_wday=0, tm_yday=354, tm_isdst=0)
result = time.strftime('%Y年%m月%d日 %H时%M分%S秒 %A', t2)
print(result)   # 2021-12-20 16:28:20

# PM xx:xx   上午 4:30
result = time.strftime('%p %I:%M', t2)
print(result)

5.time.strptime(时间字符串, 时间格式) - 将字符串时间转换成结构体时间

# 2017-3-24 是周几?
# '2017-3-24'
result = time.strptime('2017-3-24 PM 2:30', '%Y-%m-%d %p %I:%M')
print(result)
print(result.tm_wday)

6.time.mktime(结构体时间) - 将结构体时间转换成时间戳

print(t2)
result = time.mktime(t2)
print(result)       # 1639991023.0

from datetime import datetime, date, time, timedelta

1. 创建datetime类型的数据

1)获取当前时间

t1 = datetime.now()
print(t1, type(t1))       # 2021-12-20 17:13:10.560317  <class 'datetime.datetime'>

t2 = datetime.today()
print(t2, type(t1))       # 2021-12-20 17:13:31.792873  <class 'datetime.datetime'>

2) 直接提供时间信息

# datetime(年, 月, 日, 时=0, 分=0, 秒=0)
t3 = datetime(2018, 10, 1)
print(t3, type(t3))     # 2018-10-01 00:00:00 <class 'datetime.datetime'>

3) 通过字符串时间创建时间对象

t4 = datetime.strptime('2019-3-31 23:59:59', '%Y-%m-%d %H:%M:%S')
print(t4, type(t4))       # 2019-3-31 23:59:59   <class 'datetime.datetime'>

2. 获取时间对象具体的时间信息

print(t4.year)
print(t4.month)
print(t4.day)
print(t4.hour)
print(t4.minute)
print(t4.second)
print(t4.weekday())

3. 时间的加减操作

时间对象 -/+ timedelta(days=?, hours=?, minutes=?, seconds=?, weeks=?)

# 练习:2019-3-31 23:59:59 2秒后是什么时候
result = t4 + timedelta(seconds=2)
print(result)

# 练习:2019-3-31 23:59:59 4天是什么时候
result = t4 - timedelta(days=4)
print(result)

# 练习:2019-3-31 23:59:59 一周后是什么时候
result = t4 + timedelta(weeks=1)
print(result)

# 练习:2019-3-31 23:59:59 5天2小时30分钟后是什么时候
result = t4 + timedelta(days=5, hours=2, minutes=30)
print(result)

1. 哈希加密(摘要)的特点

“”"
1)密文不可逆
2)相同的数据通过相同的算法得到的密文相同, 不相同的数据通过相同的算法得到的密文不相同
3)不同长度的数据通过相同的算法得到的密文长度相同
“”"

2. Python生成哈希摘要的方法

import hashlib

1) 根据算法创建hash对象

# 常用hash算法:md5和shaxxx
hash = hashlib.sha224()
hash = hashlib.md5()

2) 添加生成摘要数据

hash对象.update(二进制数据)

“”"
Python中字符串和二进制的相互转换: 二进制 - bytes
a. 字符串转二进制
方法一:bytes(字符串, ‘utf-8’)
方法二:字符串.encode()

b. 二进制转字符串
方法一:str(二进制, ‘utf-8’)
方法二:二进制.decode()
“”"

nums = '46468'
hash.update(nums.encode())
# hash.update('sjhgfjakdfasdf盛世嫡妃'.encode())

生成文件的摘要

hash.update(open(‘files/file1.txt’, ‘rb’).read())

3) 获取摘要值(获取密文)

result = hash.hexdigest()
print(result)

展示过程:

import hashlib

hash = hashlib.md5()
nums = '46468'
hash.update(nums.encode())

result = hash.hexdigest()
print(result)

作业

1.发牌

# Author:  Zhou yun he
# Time:2021/12/20 7:46 下午
import random


def game_start():
    poker = ['大王', '小王', '♠2', '♥2', '♣2', '♦2', '♠A', '♥A', '♣A', '♦A',
             '♠K', '♥K', '♣K', '♦K', '♠Q', '♥Q', '♣Q', '♦Q', '♠J', '♥J', '♣J', '♦J',
             '♠10', '♥10', '♣10', '♦10', '♠9', '♥9', '♣9', '♦9', '♠8', '♥8', '♣8', '♦8',
             '♠7', '♥7', '♣7', '♦7', '♠6', '♥6', '♣6', '♦6', '♠5', '♥5', '♣5', '♦5',
             '♠4', '♥4', '♣4', '♦4', '♠3', '♥3', '♣3', '♦3']
    new_poker = poker.copy()
    random.shuffle(poker)
    play_a = poker[0:51:3]
    new_play_a = []
    play_b = poker[1:51:3]
    new_play_b = []
    play_c = poker[2:51:3]
    new_play_c = []
    last_card = poker[51:]
    for x in new_poker:
        if x in play_a:
            new_play_a.append(x)
        elif x in play_b:
            new_play_b.append(x)
        elif x in play_c:
            new_play_c.append(x)
    print('玩家A:', str(new_play_a).replace('\'', ''))
    print('玩家B', str(new_play_b).replace('\'', ''))
    print('玩家C:', str(new_play_c).replace('\'', ''))
    print('底牌:', str(last_card).replace('\'', ''))


game_start()

2.加密登录展示

import hashlib


def register():
    username = input('请输入账号:')
    password = input('请输入密码:')
    all_user = eval(open('files.txt').read())  # type:list
    if username in [x['username'] for x in all_user]:
        print('注册失败,该账号已经被注册!')
        return
    hash1 = hashlib.md5()
    hash1.update(password.encode())
    result = hash1.hexdigest()
    all_user.append({'username': username, 'password': result})
    open('files.txt', 'w').write(str(all_user))
    print('注册成功!')


def login():
    username = input('请输入账号:')
    password = input('请输入密码:')
    all_user = eval(open('files.txt').read())  # type:list
    for user in all_user:
        if username == user['username']:
            break
    else:
        print('登录失败!该账号不存在!')
        return
    hash1 = hashlib.md5()
    hash1.update(password.encode())
    result = hash1.hexdigest()
    if result == user['password']:
        print('登录成功!')
    else:
        print('登录失败!密码错误!')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值