1 模块分类

  1. 标准模块,不需要你单独安装,python自带的模块
  2. 第三方模块
  3. 自己写的python  一个python文件就是一个模块

2 random模块

2.1 随机取元素

 import random
print(random.randint(10,99)) #随机取一个整数 顾头又顾尾
print(random.uniform(1,9))#取一个小数
print(random.choice('abcdefg'))#随机取一个元素,列表、字符串均可传入
stus = ['xiaojun','hailong','yangfan','tanailing','yangyue','cc']
print(random.sample(stus,2)) #返回List,随机取N个元素,列表、字符串均可传入
#运行结果
80
4.679334209523862
c
['cc', 'tanailing']

2.2 洗牌

 import random
l = list(range(1,10))
print('洗牌之前的',l)
print(random.shuffle(l))#洗牌,没有返回值(类似于List的其他方法),只能传入list
print('洗牌之后的',l)
#运行结果
洗牌之前的 [1, 2, 3, 4, 5, 6, 7, 8, 9]
None
洗牌之后的 [3, 4, 5, 8, 9, 6, 1, 7, 2]

3 OS模块

3.1 文件文件夹

 import os
os.rename(old,new)#重命名
os.remove(f)#删除文件
os.mkdir('japan/tokyou') #创建文件夹,父目录不存在会报错
os.makedirs('japan/tokyou') #父目录不存在的时候会帮你创建
os.removedirs('china')#只能删除空文件夹,否则会报错
print(os.listdir())#显示该目录下面的所有文件和文件夹
print(os.path.isdir('china'))#判断是否是文件夹,不存在也返回False
print(os.path.isfile('china'))#判断是否是文件,不存在也返回False
print(os.path.exists('china'))#判断文件或者文件夹是否存在

3.2 其他操作

 import os
res = os.system('ipconfig')#执行操作系统命令,返回值为“退出状态码”
print('os.system()结果',res)
res = os.popen('ipconfig')#用来执行操作系统命令,返回值为脚本执行过程中的输出内容,返回的是file对象
print('获取脚本执行过程中的返回值:',res.read()) print('拼路径',os.path.join('china','beijing','haidian','changping','a.py'))#拼路径,兼容不同系统
res = os.path.split(r'china\beijing\haidian\西二旗\b.py')#用来分割文件名和路径
print('分割文件名和路径:',res)
res = os.path.dirname(r'china\beijing\haidian\西二旗\b.py')#取父目录,参数不能只写文件名
print('取父目录',res)
res = os.path.abspath('test.py') #取绝对路径,后面可以只跟同目录下的文件名
print(os.path.getsize('test.py'))#文件大小,单位是字节
print(os.getcwd())#取当前的目录
print(os.chdir(r'D:\我的文档\day6'))#进入到哪个目录下,没有返回值
print(os.getcwd())#取当前的目录
#执行结果
Windows IP ���� ���߾����������� ������������: �����ض��� DNS ��׺ . . . . . . . :
IPv4 ��ַ . . . . . . . . . . . . : 192.168.1.100
...... os.system()结果 0
获取脚本执行过程中的返回值:
Windows IP 配置 无线局域网适配器 无线网络连接: 连接特定的 DNS 后缀 . . . . . . . :
IPv4 地址 . . . . . . . . . . . . : 192.168.1.100
子网掩码 . . . . . . . . . . . . : 255.255.255.0
...... 拼路径 china\beijing\haidian\changping\a.py
分割文件名和路径: ('china\\beijing\\haidian\\西二旗', 'b.py')
取父目录 china\beijing\haidian\西二旗
1542
E:\PycharmProjects\test\day6
None
D:\我的文档\day6 Process finished with exit code 0

3.3  目录遍历

 import os
res = os.walk(r'E:\PycharmProjects\test\day6\china')
for cur_path, dirs, files in res:
print('当前目录', cur_path)
print('当前目录下所有文件', files)
print('当前目录下所有文件夹', dirs)
#运行结果
当前目录 E:\PycharmProjects\test\day6\china
当前目录下所有文件 []
当前目录下所有文件夹 ['beijing']
当前目录 E:\PycharmProjects\test\day6\china\beijing
当前目录下所有文件 []
当前目录下所有文件夹 ['haidian']
当前目录 E:\PycharmProjects\test\day6\china\beijing\haidian
当前目录下所有文件 []
当前目录下所有文件夹 ['西二旗']
当前目录 E:\PycharmProjects\test\day6\china\beijing\haidian\西二旗
当前目录下所有文件 []
当前目录下所有文件夹 []

例1:

 #获取E盘下有多少个Python文件
import os
res = os.walk(r'E:')
count = 0
for cu_path, dirs, files in res:
for f in files:
if f.endswith('.py'):
#if '.py' in f: 方法二
count += 1
print(count)

例2:

 #查询指定文件的目录
import os
def find_file(path,keyword):
res = os.walk(path)
for cur_path, dirs, files in res:
for file_name in files:
if keyword in file_name:
print('该文件在 %s下面' %cur_path)
find_file('D:','a.py')

4 time模块

4.1 概念

  • 格式化好的时间: 2018-09-15 14:08:53
  • 时间戳:从计算机诞生那天到现在过了多少秒
 import time
res1 = time.strftime('%y%m%d')#取当前的格式化日期,会按指定格式显示
res2 = time.strftime('%Y-%m-%d %H:%M:%S') #取当前的格式化时间,注意大小写
res3 = time.time() #获取当前时间戳 毫秒级
res4 = int(res3)#时间戳取到秒为止 print('当前日期',res1)
print('当前时间',res2)
print('当前时间戳',res3)
print('当前时间戳(秒)',res4)
#运行结果
当前日期 180919
当前时间 2018-09-19 21:13:26
当前时间戳 1537362806.048166
当前时间戳(秒) 1537362806

4.2 格式化时间-->时间戳

  • 格式化时间转换为时间戳时,要先转换成时间元组,然后从时间元组转换成时间戳
 import time
time_tuple = time.strptime('2038-08-29 19:23:59','%Y-%m-%d %H:%M:%S')#把格式化好的时间转成时间元组
print(time.mktime(time_tuple))#时间元组转换成时间戳
#运行结果
2166693839.0
  • 格式化时间转换成时间戳方法
 #格式化时间转换成时间戳方法
import time
def str_to_timestamp(time_str = None, format = '%Y-%m-%d %H%M%S'):
if time_str:
time_tuple = time.strptime(time_str, format)#转换成时间元组
timestamp = time.mktime(time_tuple)#转换成时间戳
else:
timestamp = time.time()#获取当前时间戳
return int(timestamp)
print(str_to_timestamp())
print(str_to_timestamp('2039-11-23 175123'))
#运行结果
1537364314
2205654683

4.3  时间戳-->格式化时间

  • 时间戳转换成格式化时间,也要先转换成时间元组,然后从时间元组再转换成格式化时间
 import time
res = time.gmtime(20198312)#转换成时间元组
res2 = time.strftime('%Y-%m-%d %H:%M:%S',res)#时间元组转换成格式化时间
print(res2) res = time.gmtime(time.time())#是把时间戳转时间元组的,标准时区
res = time.localtime(time.time())#是把时间戳转时间元组的,当前时区
res2 = time.strftime('%Y-%m-%d %H:%M:%S',res)
print(res2)
#运行结果
1970-08-22 18:38:32
2018-09-19 21:54:39
  • 时间戳转换成格式化时间方法
 import time
def timestamp_to_strtime(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
#这个函数是用来把时间戳转成格式化好的时间
#如果不传时间戳的话,那么就返回当前的时间
if timestamp:
time_tuple = time.localtime(timestamp)
str_time = time.strftime(format,time_tuple)
else:
str_time = time.strftime(format)
return str_time #当前的时间-3天
three = str_to_timestamp() - (3*24*60*60) #当前时间转换成时间戳-3天
res = timestamp_to_strtime(three)
print('3天前的时间是',res)

4.4 strftime和strptime方法

 import time
#strftime方法
res = time.strftime('%y%m%d') #取当前的格式化日期
res = time.strftime('%Y-%m-%d %H:%M:%S',time_tuple) #将时间元组转换成格式化时间
#strptime方法
time_tuple = time.strptime('', '%Y%m%d')#把格式化好的时间转成时间元组

5 hashlib加密

5.1 加密

 import hashlib
#python2中是md5 即import md5
password = ''
print(password.encode()) #对password进行编码,返回bytes字符串,这样才能加密
m1 = hashlib.md5(password.encode()) #MD5加密,不可逆,网上的解码都是利用撞库来实现的
m2 = hashlib.sha1(password.encode()) #sha1加密
m3 = hashlib.sha224(password.encode())
m4 = hashlib.sha256(password.encode())
print(m1.hexdigest()) #十六进制摘要
print(m2.hexdigest())
print(m3.hexdigest())
print(m4.hexdigest())
#运行结果
b'123456'
e10adc3949ba59abbe56e057f20f883e
7c4a8d09ca3762af61e59520943dc26494f8941b
f8cdb04495ded47615258f9dc6a3f4707fd2405434fefc3cbf4ef4e6
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92  

注:不知道变量有哪些方法,可用dir()查看

print(dir(m))

5.2 加盐

 def my_md5(s:str,salt=None):
#salt是盐值
s = str(s)
if salt:
s = s+salt
m = hashlib.md5(s.encode())
return m.hexdigest()

6 第三方模块

安装方法

1、pip install xxxx
2、.whl文件
pip install c:/user/niuhanyang/desktop/xxx.whl
3、.tar.gz
  1、先解压
  2、解压之后在命令行里面进入到这个目录下
  3、执行python setup.py install

7 xpinyin

 import xpinyin
s = xpinyin.Pinyin()
print(s.get_pinyin('小军',''))
#运行结果
xiaojun
 import xpinyin
p = xpinyin.Pinyin()
print(p.get_initials('上海',''))
print(p.get_initials('上海','').lower())
print(p.get_initials('上海','_'))
print(p.get_initials('上海'))
#运行结果
SH
sh
S_H
S-H

8 pymysql

8.1 参数说明

pymysql.Connect()参数说明
host(str): MySQL服务器地址
port(int): MySQL服务器端口号
user(str): 用户名
passwd(str): 密码
db(str): 数据库名称
charset(str): 连接编码 connection对象支持的方法
cursor() 使用该连接创建并返回游标
commit() 提交当前事务
rollback() 回滚当前事务
close() 关闭连接 cursor对象支持的方法
execute(op) 执行一个数据库的查询命令
fetchone() 取得结果集的下一行
fetchmany(size) 获取结果集的下几行
fetchall() 获取结果集中的所有行
rowcount() 返回数据条数或影响行数
close() 关闭游标对象

  

8.2 查

 import pymysql
host='1**.**.*.40'
user='jxz'
password='' #密码只能是字符串
db='jxz'
port=3306#端口号只能写int类型
charset='utf8'#只能写utf8,不能写utf-8
conn = pymysql.connect(host=host,password=password,
user=user,db=db,port=port,
charset=charset,autocommit=True
)#建立连接
cur= conn.cursor() #建立游标
sql='select * from app_myuser limit 5;'
cur.execute(sql)#执行sql语句
print(cur.description)#获取这个表里面的所有字段信息
print('fetchone:',cur.fetchone())#查询时获取结果集的第一行数据,返回一个元组,该元组元素即为第一行数据,如果没有则为None
print('fetchall:',cur.fetchall())#查询时获取结果集中的所有行,一行构成一个元组,然后再将这些元组返回(即嵌套元组)
print('fetchone:',cur.fetchone())#结果是None,类似于文件读写时的指针,指针已在最下面
cur.close()
conn.close()
#执行结果
(('id', 3, None, 11, 11, 0, False), ('username', 253, None, 32, 32, 0, False), ('passwd', 253, None, 32, 32, 0, False), ('is_admin', 2, None, 6, 6, 0, False))
fetchone: (1145, 'liuyana001', '123456', 1)
fetchall: ((1146, 'xd', '123456', 1), (1147, '颜无柳', '1', 1), (1148, 'pythonnjf', '123456', 1), (1149, 'gebilaowang', '123456', 1))#指针已在第二条,所以显示第二~第五条
fetchone: None

8.3 增

 import pymysql
conn = pymysql.connect(host=host,password=password,
user=user,db=db,port=port,
charset=charset,autocommit=True
)#建立连接
cur= conn.cursor() #建立游标
sql='insert into app_myuser (username,passwd,is_admin) VALUE ("p20180921","123456",1);'
cur.execute(sql)#执行sql语句
print(cur.description)#insert返回值为None
print('fetchall:',cur.fetchall())#insert无返回值
# conn.commit()#提交,connect()方法中autocommit=True,则不需要提交
cur.close()
conn.close()
#运行结果
None
fetchall:()

8.4 删

 import pymysql
conn = pymysql.connect(host=host,password=password,
user=user,db=db,port=port,
charset=charset,autocommit=True
)#建立连接
cur= conn.cursor() #建立游标
sql='delete from app_myuser where username ="p20180921";'
cur.execute(sql)#执行sql语句
print(cur.description)#insert返回值为None
print('fetchall:',cur.fetchall())#delete无返回值
# conn.commit()#提交,connect()方法中autocommit=True,则不需要提交
cur.close()
conn.close()
#运行结果
None
fetchall: ()

  

8.5 改

 import pymysql
conn = pymysql.connect(host=host,password=password,
user=user,db=db,port=port,
charset=charset,autocommit=True
)#建立连接
cur= conn.cursor() #建立游标
sql='update app_myuser set passwd = "new123456" where username ="test123";'
cur.execute(sql)#执行sql语句
print(cur.description)#insert返回值为None
print('fetchall:',cur.fetchall())#update无返回值
# conn.commit()#提交,connect()方法中autocommit=True,则不需要提交
cur.close()
conn.close()
#运行结果
None
fetchall: ()

8.6 例

#方法1
import pymysql
def my_db(ip,user,password,db,sql,port=3306,charset='utf8'):
conn = pymysql.connect(
host=ip,user=user,password=password,
db=db,
port=port,charset=charset,autocommit=True
)
cur = conn.cursor()
cur.execute(sql)
res = cur.fetchall()
cur.close()
conn.close()
return res
#方法2
import pymysql
def my_db2(sql):
conn = pymysql.connect(
host='1*.*.*.*0',user='jxz',password='',
db='jxz',
port=3306,charset='utf8',autocommit=True
)
pass

sql可使用参数化查询:

row_count=cursor.execute("select user,pass from tb7 where user=%s and pass=%s",(user,passwd)) #参数化sql语句

 sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

9 Excel

9.1 xlwt写

 import xlwt
book = xlwt.Workbook()
sheet = book.add_sheet('sheet1')
sheet.write(0,0,'id')#指定行和列写内容
sheet.write(0,1,'username')
sheet.write(0,2,'password')
sheet.write(1,0,'')
sheet.write(1,1,'niuhanyang')
sheet.write(1,2,'')
book.save('stu01.xls')# .xlsx 写入excel文件

例:

 import xlwt
stus = [
[1,'njf',''],
[2,'xiaojun',''],
[3,'hailong',''],
[4,'xiaohei','']
]
book = xlwt.Workbook()
sheet = book.add_sheet('sheet01')
line = 0 #控制的是行
for stu in stus:#行
col = 0#控制列
for s in stu:
sheet.write(line,col,s)
col+=1
line+=1
book.save('stu02.xls')# .xlsx

9.2 xlrd读

 import xlrd
book = xlrd.open_workbook('stu.xls')
sheet = book.sheet_by_index(0)
# sheet = book.sheet_by_name('sheet1')
print(sheet.nrows) #excel里面有多少行
print(sheet.ncols) #excel里面有多少列 print(sheet.cell(0,0).value) #获取到指定单元格的内容
print(sheet.cell(0,1).value) #获取到指定单元格的内容 print("row_values: ",sheet.row_values(0))#获取到整行的内容
print("col_values: ",sheet.col_values(0))#获取到整列的内容 for i in range(sheet.nrows):#循环获取每行的内容
print(i+1,'行:',sheet.row_values(i))
#运行结果
9
3
1.0
njf
row_values: [1.0, 'njf', '1234']
col_values: [1.0, 2.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0]
1 行: [1.0, 'njf', '1234']
2 行: [2.0, 'xiaojun', '1234']
3 行: [3.0, 'hailong', '1234']
4 行: [4.0, 'xiaohei', '1234']
5 行: [4.0, 'xiaohei', '1234']
6 行: [4.0, 'xiaohei', '1234']
7 行: [4.0, 'xiaohei', '1234']
8 行: [4.0, 'xiaohei', '1234']
9 行: [4.0, 'xiaohei', '1234']

9.3 xlutils 改

 import xlrd
from xlutils import copy
book = xlrd.open_workbook('stu.xls')#先用xlrd打开一个Excel
new_book = copy.copy(book)#然后用xlutils里面的copy功能,复制一个Excel
sheet = new_book.get_sheet(0)#获取sheet页
sheet.write(0,1,'倪菊芳')
sheet.write(1,1,'白小军')
new_book.save('stu.xls')

10 列表生成式

 res = [ str(i).zfill(2) for i in range(1,34)]
l = [ i for i in range(10) ]
print(l)
print(res)
#运行结果
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33']

  

11 修改PIP源

 import os,sys,platform
ini="""[global]
index-url = https://pypi.doubanio.com/simple/
[install]
trusted-host=pypi.doubanio.com
"""
os_version=platform.platform()
if 'Windows' in os_version:
os_flag=False
file_name='pip.ini'
else:
os_flag=True
file_name='pip.conf'
if os_flag==True:
pippath=os.environ["HOME"]+os.sep+".pip"+os.sep
else:
pippath=os.environ["USERPROFILE"]+os.sep+"pip"+os.sep
if not os.path.exists(pippath):
os.mkdir(pippath)
with open(pippath+file_name,"w") as f:
f.write(ini)

【05】Python 标准模块:random、os、time、hashlib 第三方模块:excel、数据库 列表生成式的更多相关文章

  1. Python全栈--7模块--random os sys time datetime hashlib pickle json requests xml

    模块分为三种: 自定义模块 内置模块 开源模块 一.安装第三方模块 # python 安装第三方模块 # 加入环境变量 : 右键计算机---属性---高级设置---环境变量---path--分号+py ...

  2. 常用模块(random,os,json,pickle,shelve)

    常用模块(random,os,json,pickle,shelve) random import random print(random.random()) # 0-1之间的小数 print(rand ...

  3. 模块random+os+sys+json+subprocess

    模块random+os+sys+json+subprocess 1. random 模块   (产生一个随机值) import random 1 # 随机小数 2 print(random.rando ...

  4. Python常用模块(time, datetime, random, os, sys, hashlib)

    time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp) :         通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运 ...

  5. python基础语法11 内置模块time,datatime,random,os,sys,hashlib模块

    time模块 在python的三种时间表现形式: 1.时间戳: 给电脑看的. - 自1970-01-01 00:00:00到当前时间,按秒计算,计算了多少秒. 2.格式化时间(Format Strin ...

  6. 常用模块random/os/sys/time/datatime/hashlib/pymysql等

    一.标准模块 1.python自带的,import random,json,os,sys,datetime,hashlib等 ①.正常按照命令:打开cmd,执行:pip install rangdom ...

  7. CSIC_716_20191116【常用模块的用法 time ,datetime, random, os, sys, hashlib】

    import time import datetime import os import sys import random import hashlib time模块 时间戳(Timestamp) ...

  8. time,datetime,random,os,sys,hashlib,logging,configparser,re模块

    #-----time模块----- print(help(time)) #打印time帮助文档 print(time.time()) #打印时间戳 1569824501.6265268 time.sl ...

  9. 时间模块 time 随机模块random os模块,sys模块

    时间模块  time #时间模块 import time #三种格式 #时间戳时间:是一个浮点数,以秒为单位,计算机用语 #结构化时间 :是一个元组 #用于中间转换 #格式化时间:str数据类型, 用 ...

随机推荐

  1. np.random.shuffle(x)与np.random.permutation(x)

    来自:https://blog.csdn.net/brucewong0516/article/details/79012233 将数组打乱随机排列 两种方法: np.random.shuffle(x) ...

  2. k8s架构

    master节点 k8s的集群由master和node组成,节点上运行着若干k8s服务. master节点之上运行着的后台服务有kube-apiserver .kube-scheduler.kube- ...

  3. 针对WordPress站点思路

    一.使用WPscan 1).简介 WPScan是一个扫描 WordPress 漏洞的黑盒子扫描器,它可以为所有 Web 开发人员扫描 WordPress 漏洞并在他们开发前找到并解决问题.我们还使用了 ...

  4. Web安全测试中常见逻辑漏洞解析(实战篇)

    Web安全测试中常见逻辑漏洞解析(实战篇) 简要: 越权漏洞是比较常见的漏洞类型,越权漏洞可以理解为,一个正常的用户A通常只能够对自己的一些信息进行增删改查,但是由于程序员的一时疏忽,对信息进行增删改 ...

  5. python下对文件的操作(非目录)

    总文件夹 子文件夹01 文档01.txt-------------------------------------------------------------------------------- ...

  6. Oracle 高版本往低版本备份恢复的方法

    1. 高版本的数据库备份恢复到低版本的数据库 有时候回报错, 提示version版本不一致, 2. 其实方法是expdp 导出的时候 增加一个参数就可以了 参数 一般的类型是 version=11.2 ...

  7. 【错误】jsp查询字符串中空格导致的异常问题!

    jsp中查询字符串中空格问题 jsp中查询字符串中参数名的等号右边最好不要出现空格,因为编译器会把他当做是参数值得一部分. 例如: <a href="adjust.jsp?number ...

  8. SQL查询结果列拼接成逗号分隔的字符串:group_concat

    转自:SQL查询结果列拼接成逗号分隔的字符串 背景:做SQL查询时会经常需要,把查询的结果拼接成一个字符串. 解决方法: 通过 group_concat 函数 拼接的结果很长,导致拼接结果显示不全,可 ...

  9. Qt 遍历不规则树的节点

    在使用Qt的GraphicsScene作图时,遇到类似这样的需求:在scene中创建节点类似下图, 现在我要把每个节点的txt保存到xml文件中,结构为 <?xml version='1.0' ...

  10. 本地代码推送到远程git仓库

    # 1. 在远程新建一个代码仓库(如码云,github..) # 2. 将本地代码提交 git init git add * git commit -am "first init" ...