1、chr()和ord()
# ord() print(ord('a')) print(ord('A')) print(ord('段'))print(ord('刚')) # chr() print(chr(22270)) print(chr(122))
2、时间模块
1>time
得到秒的表示time.time() 当前时间的秒的表示形式
time.localtime(seconds) ------>tuple
time.strftime(format,tuple) ------>string
import time import os print(time.time()) print(os.path.getatime(r'C:imagesdesk_background.jpg')) # 访问时间 print(os.path.getctime(r'C:imagesdesk_background.jpg')) # 创建时间 windows print(os.path.getmtime(r'C:imagesdesk_background.jpg')) # 修改时间 t = os.path.getmtime(r'C:imagesdesk_background.jpg') st = time.localtime(t) print(st.tm_yday) print(time.asctime(st)) # Mon May 27 17:54:26 2019 print(time.strftime('%Y-%m-%d %H:%M:%S', st))
2>datetime:模块
4个类:
date 日期
time 时间
timedelta 时间差
datetime 日期和时间
from datetime import datetime, timedelta print(datetime.now()) print(datetime.today()) import sys print(sys.version_info) print(sys.version) print(sys.path) dt = datetime.now() tdt = timedelta(minutes=30) print(dt - tdt)
3、日历相关
import calendar print(calendar.calendar(2019)) print(calendar.month(2019, 8)) print(calendar.weekday(2019, 8, 12)) # 星期几 星期一从0开始的
4、os模块
mkdir()
rmdir() 非空: OSError: 目录不是空的
递归的方式
import shutil
shutil.rmtree()
os.listdir(path) 查看path下的内容,并以列表的形式返回
os.getcwd() 获取当前文件的路径(绝对路径)
os.getpid() get process id 获取当前进程号
os.getpid() get parent process id 获取父进程号
os.chdir() 切换目录
import os # print(os.name) # try: # os.mkdir('t2') # os.mkdir('c:/foo') # except FileExistsError: # print('文件夹已经存在!!') # os.rmdir('c:/foo') # 递归删除目录及文件 # import shutil # shutil.rmtree(r'路径名') # files = os.listdir(r'd:video') # print(files) # # print(os.getcwd()) # # print(os.getpid()) # print(os.getppid()) # # os.chdir('d:/video1') # 切换目录
# 也可以递归删除文件 def delAll(path): if os.path.isdir(path): files = os.listdir(path) # ['a.doc', 'b.xls', 'c.ppt'] # 遍历并删除文件 for file in files: p = os.path.join(path, file) if os.path.isdir(p): # 递归 delAll(p) else: os.remove(p) # 删除文件夹 os.rmdir(path) else: os.remove(path)
path = r'd:videopythona.png' print(os.path.split(path)[1]) # print(os.path.getsize('')) # 得到文件的大小 # print(os.environ) # # print(os.path.abspath('a.txt') ) # 绝对路径 # print(os.path.isabs('a.txt')) # 判断给的路径是否是绝对路径 # print(os.path.isfile('a.txt')) # 是否为文件 # print(os.path.isdir('a.txt')) # 是否是文件夹 # print(os.path.exists('t2'))
5、随机数模块
randint(a,b) --->[a,b]
randrange(a,b) ---> [a,b)
random() --->小数 [0,1)
choice()
shuffle(seq) --> 打乱顺序seq的顺序
import random print(random.randrange(1, 10)) print(random.randint(1, 10)) print(random.random()) # [0,1) print(random.choice('ancefhdjkflg')) list1 = [1, 2, 3, 4, 5, 6, 7, 8] random.shuffle(list1) print(list1)
6、math 和数学相关的模块
import math print(math.ceil(9.12)) print(math.floor(9.89)) print(math.fmod(10, 3)) # 求余数 print(math.fabs(-89)) print(math.sqrt(16)) # sqrt(x),对x开平方 print(math.pow(2, 5)) # pow(x,y) x的y次方 # sum() # abs() # round() 四舍五入
7、hashlib模块------加密(md5 sha1 sha256)都是不可逆的
import hashlib md5 = hashlib.md5() s = '你好,微笑天使:何思雨' a = md5.update(s.encode('utf-8')) print(md5.digest()) print(md5.hexdigest()) ''' 注冊: 用戶名: 密碼: ----数据库 admin 123456 ''' sha1 = hashlib.sha1(s.encode('utf-8')) print(sha1.hexdigest()) sha256 = hashlib.sha256(s.encode('utf-8')) print(sha256.hexdigest()) print(len(sha256.hexdigest()))
用例:使用csv保存用户名和密码并加密
''' 用户注册和登录 ''' import csv import hashlib def register(): username = input('用户名:') password = input('密码:') user = [] user.append(username) user.append(hashlib.sha256(password.encode('utf-8')).hexdigest()) with open('t2/users.csv','a',newline='') as ws: csv_ws = csv.writer(ws) csv_ws.writerow(user) print('注册成功!!!') def login(): username = input('用户名:') password = input('密码:') password = hashlib.sha256(password.encode('utf-8')).hexdigest() with open('t2/users.csv','r',newline='') as rs: csv_rs = csv.reader(rs) for user in csv_rs: if username == user[0] and password == user[1]: print('登录成功!!') break else: print('用户名或密码有误!!!') if __name__ == '__main__': # register() login()
8、日志文件:
日志级别:
'CRITICAL': CRITICAL,
'FATAL': FATAL,
'ERROR': ERROR,
'WARN': WARNING,
'WARNING': WARNING,
'INFO': INFO,
'DEBUG': DEBUG,
'NOTSET': NOTSET,
import logging # 1. 日志对象 logger = logging.getLogger() # 2. 设置级别 logger.setLevel(logging.ERROR) # 3. 创建一个handler 对象 file = 't2/log.txt' handler = logging.FileHandler(file) handler.setLevel(logging.ERROR) # 4. 创建一个formatter格式对象 fmt = logging.Formatter('%(asctime)s - %(module)s - %(filename)s[%(lineno)d] - %(levelname)s:%(message)s') handler.setFormatter(fmt) # 5. logger.addHandler(handler) def func(): try: number = int(input('请输入一个数字:')) for i in range(number): print('---->', i) except: logger.error('输入的不是一个数字!') finally: print('------over---------') func()
9、urllib模块
url:
协议://存放资源的地址(域名)/具体的资源
urllib.request 用来发出请求
urllib.parse
urllib.request.urlopen(str) --->response对象
request= urllib.request.Request(url,data,headers)
urllib.request.urlopen(request) --->response对象
从response中获取信息
response.read() ----> 字节信息
要对信息进行解码:
response.read().decode('utf-8')
import urllib.request import urllib.parse # response = urllib.request.urlopen('https://bj.lianjia.com/zufang/BJ2319485348977049600.html?nav=0') url = 'https://bj.lianjia.com/zufang/BJ2319485348977049600.html' header = {} header[ 'User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36' data = {} data['nav'] = 0 data = urllib.parse.urlencode(data).encode('utf-8') # 创建请求对象 request = urllib.request.Request(url, data, header) response = urllib.request.urlopen(request) content = response.read() # print(content) print(content.decode('utf-8'))