python12 模块

python12 模块

一个模块就是一个xxx.py文件
模块名起名的时候必须要遵循命名规则。
a1.py a_1.py a+1.py
在一个模块中可以存着多个变量,多个函数,多个类
如果B模块想使用A模块中的test函数,如何将A模块中test函数引入?
import 模块名
python 内置标准库中常用的模块有哪些?

random

import random

# 获取[0,1)之间的小数
ran = random.random()
print(ran)  # 0.6322115963818896

code = ''
s = 'qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM'
for i in range(4):
    ran = random.choice(s)
    print(ran)
    code += ran
print(code)
'''
K
D
N
J
KDNJ
'''

names = ['京京', '宗老大', '坤坤', '阿涛']
name = random.choice(names)
print('表演节目的是:', name)  # 表演节目的是: 阿涛

name = random.sample(names, 2)  # 指定个数的随机获取元素
print('表演节目的是:', name)  # 表演节目的是: ['宗老大', '阿涛']

r = random.randrange(1, 20)  # 给定范围回去随机数randrange(start,stop,step=1)
print(r)  # 7

r = random.randint(1, 20)
print(r)  # 12

r = random.uniform(1, 20)
print(r)  # 7.549143777340065

randrange与randint的区别:

  • randrange为前闭后开区间,可以加step取值步长
  • randint为闭区间

math

数学模块
方便一些数据计算

import math

print(math.pi)  # 3.141592653589793
r = 12.89636
print(math.ceil(r))  # 13 向上取整
print(math.floor(r))  # 12 向下取整
print(math.factorial(4))  # 12 阶乘
print(math.pow(4, 3))  # 16 pow(m,n) 表示的是m的n次方
print(math.fabs(-19.65))  # 19.65 绝对值
print(math.sqrt(10))  # 3.1622776601683795 开平方
print(abs(-19.65))  # 19.65 系统函数的绝对值

builtins

默认加载模块

print()
max()
list()
str()
id()
type()

os

开发中会涉及文件和路径的操作

import os

# 新建文件夹
os.mkdir('file')  # 如果文件夹已经存在则报错 FileExistsError: [Errno 17] File exists: 'file'

# 获取当前文件所在的位置(路径)
print(os.getcwd())  # /Users/zhangyifan/Desktop/python/py/p12

# 删除文件夹
os.rmdir('file')  # 如果文件夹非空则报错 OSError: [Errno 66] Directory not empty: 'files'

# 删除文件
os.remove('file')

# 推荐删除文件夹,可以删除有内容的文件夹
import shutil

shutil.rmtree('file')

# 是否是文件夹
r = os.path.isdir('files')
print(r)  # True

# 是否是文件判断
r = os.path.isfile('files')
print(r)  # False

# 获取目录下的所有的子文件,删除文件
file_list = os.listdir('files')
print(file_list)  # ['file.txt', 'file', 'py.py']

for i in file_list:
    # os.path.join(path1,path2..)  拼接路径
    path = os.path.join(os.getcwd(), 'files', i)
    print(path)
    r = os.path.isdir(path)
    print(r)
    r = os.path.isfile(path)
    print(r)
    if os.path.isfile(path):
        os.remove(path)
print('删除完毕')
'''
/Users/zhangyifan/Desktop/python/py/p12/files/file.txt
False
True
/Users/zhangyifan/Desktop/python/py/p12/files/file
True
False
/Users/zhangyifan/Desktop/python/py/p12/files/py.py
False
True
删除完毕
'''
file_list = os.listdir('files')
print(file_list)  # ['file']

os.chdir('files')  # 改变当前工作目录到指定的路径
open('a1.txt', 'w')  # 文件操作,没有则新建

print(os.environ)
print(os.environ.get('OS'))  # macOS没有OS
print(os.environ.get('PATH'))
'''
environ({'PATH': '/usr/local/mysql/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin', 'PYTHONPATH': '/Users/zhangyifan/Desktop/python/py', 'SHELL': '/bin/bash', 'WORKON_HOME': '/Users/zhangyifan/.virtualenvs', 'PYTHONIOENCODING': 'UTF-8', 'VIRTUALENVWRAPPER_HOOK_DIR': '/Users/zhangyifan/.virtualenvs', 'USER': 'zhangyifan', 'TMPDIR': '/var/folders/1m/sqn_23w50j56tjqn7xmbyznw0000gn/T/', 'SSH_AUTH_SOCK': '/private/tmp/com.apple.launchd.FiwrBAwbwX/Listeners', 'DISPLAY': '/private/tmp/com.apple.launchd.Dlf8iMYB2f/org.macosforge.xquartz:0', 'XPC_FLAGS': '0x0', 'PYTHONUNBUFFERED': '1', 'VIRTUALENVWRAPPER_PROJECT_FILENAME': '.project', 'VERSIONER_PYTHON_VERSION': '2.7', 'VIRTUALENVWRAPPER_WORKON_CD': '1', '__CF_USER_TEXT_ENCODING': '0x1F5:0x19:0x34', 'LOGNAME': 'zhangyifan', 'LC_CTYPE': 'zh_CN.UTF-8', 'XPC_SERVICE_NAME': 'com.jetbrains.pycharm.1228', 'PWD': '/Users/zhangyifan/Desktop/python/py/p12', 'PYCHARM_HOSTED': '1', 'HOME': '/Users/zhangyifan', '__PYVENV_LAUNCHER__': '/usr/local/bin/python3'})
None
/usr/local/mysql/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Library/Frameworks/Python.framework/Versions/3.8/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
'''

path = os.path.abspath('files')  # 绝对路径
print(path)  # /Users/zhangyifan/Desktop/python/py/p12/files

result = os.path.split(path)  # 最后一个/分割
print(result)  # ('/Users/zhangyifan/Desktop/python/py/p12', 'files')

result = os.path.dirname(path)  # 最后一个/之前
print(result)  # /Users/zhangyifan/Desktop/python/py/p12

# __file__表示目前执行文件的路径
print(__file__)  # /Users/zhangyifan/Desktop/python/py/p12/模块os_6.py
path = os.path.dirname(os.path.dirname(__file__))
print(path)  # /Users/zhangyifan/Desktop/python/py

result = os.path.split(__file__)
print(result)  # ('/Users/zhangyifan/Desktop/python/py/p12', '模块os_6.py')

result = os.path.splitext(__file__)  # 最后一个.分割
print(result)  # ('/Users/zhangyifan/Desktop/python/py/p12/模块os_6', '.py')

result = os.path.splitext(__file__)
print(result[1])  # .py

time

import time

# 时间戳 1970-1-1 00:00:00 到现在毫秒值
print(time.time())  # 1580546820.1580968
time.sleep(1)
print(time.time())  # 1580546821.159769

print(time.asctime())  # Sat Feb  1 16:47:01 2020
t = time.localtime(time.time())
print(t)  # time.struct_time(tm_year=2020, tm_mon=2, tm_mday=1, tm_hour=16, tm_min=50, tm_sec=58, tm_wday=5, tm_yday=32, tm_isdst=0)
print(time.strftime('%Y/%m/%d %H:%M:%S  %a', t))  # 2020/02/01 16:50:58  Sat
'''
%Y  year
%m  month
%d  day

%H  时
%M  分
%S  秒
'''

datetime

import datetime

# 获取当前日期时间,格式化后的
print(datetime.datetime.now())  # 2020-02-01 17:11:43.780367
print(datetime.datetime.now().hour)  # 17

# 时间差
print(datetime.timedelta(days=5, minutes=10))  # 5 days, 0:10:00

last = datetime.datetime.now() - datetime.timedelta(days=4)
print(last)  # 2020-01-28 17:11:43.781007

future = datetime.datetime.now() + datetime.timedelta(days=4)
print(future)  # 2020-02-05 17:16:04.422009

t = datetime.time(hour=10, minute=3, second=30)
print(t)  # 10:03:30
print(t.hour)  # 10

d = datetime.date(year=2019, month=12, day=25)
print(d)  # 2019-12-25
print(d.month)  # 12

calendar

日历

import calendar

calendar.setfirstweekday(calendar.SUNDAY)
c = calendar.calendar(2020)  # 生成2019年的日历,并且以周日为起始日期
print(c)  # 打印2019年日历
'''
                                  2020

      January                   February                   March
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
          1  2  3  4                         1       1  2  3  4  5  6  7
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       8  9 10 11 12 13 14
12 13 14 15 16 17 18       9 10 11 12 13 14 15      15 16 17 18 19 20 21
19 20 21 22 23 24 25      16 17 18 19 20 21 22      22 23 24 25 26 27 28
26 27 28 29 30 31         23 24 25 26 27 28 29      29 30 31

       April                      May                       June
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
          1  2  3  4                      1  2          1  2  3  4  5  6
 5  6  7  8  9 10 11       3  4  5  6  7  8  9       7  8  9 10 11 12 13
12 13 14 15 16 17 18      10 11 12 13 14 15 16      14 15 16 17 18 19 20
19 20 21 22 23 24 25      17 18 19 20 21 22 23      21 22 23 24 25 26 27
26 27 28 29 30            24 25 26 27 28 29 30      28 29 30
                          31

        July                     August                  September
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
          1  2  3  4                         1             1  2  3  4  5
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       6  7  8  9 10 11 12
12 13 14 15 16 17 18       9 10 11 12 13 14 15      13 14 15 16 17 18 19
19 20 21 22 23 24 25      16 17 18 19 20 21 22      20 21 22 23 24 25 26
26 27 28 29 30 31         23 24 25 26 27 28 29      27 28 29 30
                          30 31

      October                   November                  December
Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa      Su Mo Tu We Th Fr Sa
             1  2  3       1  2  3  4  5  6  7             1  2  3  4  5
 4  5  6  7  8  9 10       8  9 10 11 12 13 14       6  7  8  9 10 11 12
11 12 13 14 15 16 17      15 16 17 18 19 20 21      13 14 15 16 17 18 19
18 19 20 21 22 23 24      22 23 24 25 26 27 28      20 21 22 23 24 25 26
25 26 27 28 29 30 31      29 30                     27 28 29 30 31
'''

# 闰年判断
print(calendar.isleap(2020))  # True

print(calendar.month(2019, 12))
'''
   December 2019
Su Mo Tu We Th Fr Sa
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
'''

uuid

唯一标识符

  • uuid1() 时间戳+随机数+Mac地址 唯一
  • uuid4() 随机数 会重复
import uuid

u1 = uuid.uuid1()
print(u1)  # e320199a-44d1-11ea-818c-a45e60bf535f
print(type(u1))  # <class 'uuid.UUID'>
u1 = str(u1)
u1 = u1.replace('-', '')
print(u1)  # e320199a44d111ea818ca45e60bf535f

u4 = uuid.uuid4()
print(u4)  # a838116e-3c77-418a-8a0b-35db7422bbae
print(str(u4).replace('-', ''))  # a838116e3c77418a8a0b35db7422bbae

# 基于名字的UUID MD5
print(uuid.uuid3(uuid.NAMESPACE_DNS, 'hello111'))  # 0e30cbeb-2230-399c-b50e-88429d8bd9b4
# 基于名字的UUID SHA1
print(uuid.uuid5(uuid.NAMESPACE_DNS, 'hello111'))  # eb1b0499-40a5-5dcb-a8d3-4cb0e61cdaea

base64

加密

import base64

s = '小潘潘、冯提莫、葛雨晴'

r1 = base64.b16encode(s.encode('utf-8'))
r2 = base64.b85encode(s.encode('utf-8'))

print(r1)  # b'E5B08FE6BD98E6BD98E38081E586AFE68F90E88EABE38081E8919BE99BA8E699B4'
print(r2)  # b'<*<+Dy_n{`nB#zf<%X~3kC5n&tK)!y=#iW0o2cfQv;'

x1 = base64.b16decode(r1)
print(x1.decode('utf-8'))  # 小潘潘、冯提莫、葛雨晴

x2 = base64.b85decode(r2)
print(x2.decode('utf-8'))  # 小潘潘、冯提莫、葛雨晴

hashlib

  • md5
    步骤:
    1. 创建md5对象
    2. 将要加密的信息传递给update函数
    3. 获取加密结果
    # 1.创建md5对象
    md5 = hashlib.md5()
    # 2.将要加密的信息传递给update函数
    s = '123456'
    md5.update(s.encode('utf-8'))
    # 3. 获取加密后结果
    result = md5.hexdigest()
    print(result)  # e10adc3949ba59abbe56e057f20f883e
    
    # 第二种使用方式
    s1 = '123456'
    md5 = hashlib.md5(s1.encode('utf-8'))
    result = md5.hexdigest()
    print(result)
    
  • sha1 sha256 sha512
    sha1 = hashlib.sha1(s.encode('utf-8'))
    result = sha1.hexdigest()
    print(result)  # 7c4a8d09ca3762af61e59520943dc26494f8941b
    
    sha256 = hashlib.sha256(s.encode('utf-8'))
    result = sha256.hexdigest()
    print(result)  # 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
    
    sha512 = hashlib.sha512(s.encode('utf-8'))
    result = sha512.hexdigest()
    print(result)  # ba3253876aed6bc22d4a6ff53d8406c6ad864195ed144ab5c87621b6c233b548baeae6956df346ec8c17f5ea10f35ee3cbc514797ed7ddd3145464e2a0bab413
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值