【05】Python 标准模块:random、os、time、hashlib 第三方模块:excel、数据库 列表生成式、修改pip源

1 模块分类

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

2 random模块

2.1 随机取元素

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

2.2 洗牌

1 import random
2 l = list(range(1,10))
3 print('洗牌之前的',l)
4 print(random.shuffle(l))#洗牌,没有返回值(类似于List的其他方法),只能传入list
5 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 文件文件夹

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

 3.2 其他操作

 1 import os
 2 res = os.system('ipconfig')#执行操作系统命令,返回值为“退出状态码”
 3 print('os.system()结果',res)
 4 res = os.popen('ipconfig')#用来执行操作系统命令,返回值为脚本执行过程中的输出内容,返回的是file对象
 5 print('获取脚本执行过程中的返回值:',res.read())
 6 
 7 print('拼路径',os.path.join('china','beijing','haidian','changping','a.py'))#拼路径,兼容不同系统
 8 res = os.path.split(r'chinaeijinghaidian西二旗.py')#用来分割文件名和路径
 9 print('分割文件名和路径:',res)
10 res = os.path.dirname(r'chinaeijinghaidian西二旗.py')#取父目录,参数不能只写文件名
11 print('取父目录',res)
12 res = os.path.abspath('test.py') #取绝对路径,后面可以只跟同目录下的文件名
13 print(os.path.getsize('test.py'))#文件大小,单位是字节
14 print(os.getcwd())#取当前的目录
15 print(os.chdir(r'D:我的文档day6'))#进入到哪个目录下,没有返回值
16 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
......

拼路径 chinaeijinghaidianchangpinga.py
分割文件名和路径: ('china\beijing\haidian\西二旗', 'b.py')
取父目录 chinaeijinghaidian西二旗
1542
E:PycharmProjects	estday6
None
D:我的文档day6

Process finished with exit code 0

3.3  目录遍历

1 import os
2 res = os.walk(r'E:PycharmProjects	estday6china')
3 for cur_path, dirs, files in res:
4     print('当前目录', cur_path)
5     print('当前目录下所有文件', files)
6     print('当前目录下所有文件夹', dirs)
#运行结果
当前目录 E:PycharmProjects	estday6china
当前目录下所有文件 []
当前目录下所有文件夹 ['beijing']
当前目录 E:PycharmProjects	estday6chinaeijing
当前目录下所有文件 []
当前目录下所有文件夹 ['haidian']
当前目录 E:PycharmProjects	estday6chinaeijinghaidian
当前目录下所有文件 []
当前目录下所有文件夹 ['西二旗']
当前目录 E:PycharmProjects	estday6chinaeijinghaidian西二旗
当前目录下所有文件 []
当前目录下所有文件夹 []

 例1:

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

例2:

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

4 time模块

4.1 概念

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

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

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

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

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

4.4 strftime和strptime方法

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

5 hashlib加密

5.1 加密

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

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

print(dir(m))

5.2 加盐

1 def my_md5(s:str,salt=None):
2     #salt是盐值
3     s = str(s)
4     if salt:
5         s = s+salt
6     m = hashlib.md5(s.encode())
7     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 

1 import xpinyin
2 s = xpinyin.Pinyin()
3 print(s.get_pinyin('小军',''))
#运行结果
xiaojun
1 import xpinyin
2 p = xpinyin.Pinyin()
3 print(p.get_initials('上海',''))
4 print(p.get_initials('上海','').lower())
5 print(p.get_initials('上海','_'))
6 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 查

 1 import pymysql
 2 host='1**.**.*.40'
 3 user='jxz'
 4 password='123456' #密码只能是字符串
 5 db='jxz'
 6 port=3306#端口号只能写int类型
 7 charset='utf8'#只能写utf8,不能写utf-8
 8 conn = pymysql.connect(host=host,password=password,
 9                 user=user,db=db,port=port,
10                 charset=charset,autocommit=True
11                 )#建立连接
12 cur= conn.cursor() #建立游标
13 sql='select * from app_myuser limit 5;'
14 cur.execute(sql)#执行sql语句
15 print(cur.description)#获取这个表里面的所有字段信息
16 print('fetchone:',cur.fetchone())#查询时获取结果集的第一行数据,返回一个元组,该元组元素即为第一行数据,如果没有则为None
17 print('fetchall:',cur.fetchall())#查询时获取结果集中的所有行,一行构成一个元组,然后再将这些元组返回(即嵌套元组)
18 print('fetchone:',cur.fetchone())#结果是None,类似于文件读写时的指针,指针已在最下面
19 cur.close()
20 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 增

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

8.4 删

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

  

8.5 改

 1 import pymysql
 2 conn = pymysql.connect(host=host,password=password,
 3                 user=user,db=db,port=port,
 4                 charset=charset,autocommit=True
 5                 )#建立连接
 6 cur= conn.cursor() #建立游标
 7 sql='update app_myuser set passwd = "new123456" where username ="test123";'
 8 cur.execute(sql)#执行sql语句
 9 print(cur.description)#insert返回值为None
10 print('fetchall:',cur.fetchall())#update无返回值
11 # conn.commit()#提交,connect()方法中autocommit=True,则不需要提交
12 cur.close()
13 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='123456',
        db='jxz',
        port=3306,charset='utf8',autocommit=True
    )
    pass

 sql可使用参数化查询:

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

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

9 Excel

9.1 xlwt写

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

例:

 1 import xlwt
 2 stus = [
 3     [1,'njf','1234'],
 4     [2,'xiaojun','1234'],
 5     [3,'hailong','1234'],
 6     [4,'xiaohei','1234']
 7 ]
 8 book = xlwt.Workbook()
 9 sheet = book.add_sheet('sheet01')
10 line = 0 #控制的是行
11 for stu in stus:#
12     col = 0#控制列
13     for s in stu:
14         sheet.write(line,col,s)
15         col+=1
16     line+=1
17 book.save('stu02.xls')# .xlsx

9.2 xlrd读

 1 import xlrd
 2 book = xlrd.open_workbook('stu.xls')
 3 sheet = book.sheet_by_index(0)
 4 # sheet = book.sheet_by_name('sheet1')
 5 print(sheet.nrows) #excel里面有多少行
 6 print(sheet.ncols) #excel里面有多少列
 7 
 8 print(sheet.cell(0,0).value) #获取到指定单元格的内容
 9 print(sheet.cell(0,1).value) #获取到指定单元格的内容
10 
11 print("row_values: ",sheet.row_values(0))#获取到整行的内容
12 print("col_values: ",sheet.col_values(0))#获取到整列的内容
13 
14 for i in range(sheet.nrows):#循环获取每行的内容
15     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 改

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

10 列表生成式

1 res = [ str(i).zfill(2) for i in range(1,34)]
2 l = [  i  for i in range(10) ]
3 print(l)
4 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源

 1 import os,sys,platform
 2 ini="""[global]
 3 index-url = https://pypi.doubanio.com/simple/
 4 [install]
 5 trusted-host=pypi.doubanio.com
 6 """
 7 os_version=platform.platform()
 8 if 'Windows' in os_version:
 9     os_flag=False
10     file_name='pip.ini'
11 else:
12     os_flag=True
13     file_name='pip.conf'
14 if os_flag==True:
15     pippath=os.environ["HOME"]+os.sep+".pip"+os.sep
16 else:
17     pippath=os.environ["USERPROFILE"]+os.sep+"pip"+os.sep
18 if not os.path.exists(pippath):
19     os.mkdir(pippath)
20 with open(pippath+file_name,"w") as f:
21     f.write(ini)
原文地址:https://www.cnblogs.com/momolei/p/9661829.html