Python常用模块

1.模块定义

什么是模块:

实质上就是一个python文件,它是用来组织代码的,意思就是说把python代码写到里面,文件名就是模块的名称,test.py test就是模块名称。

什么是包:

用来从逻辑上组织模块的,本质上就一个目录(不同的是有一个__init__.py文件)

2、导入模块

import 文件名.模块名

  (与from导入不同的是要有文件名前缀,实际上是运行了文件中的所有代码)

from 模块文件名 import *

   (导入文件的所有代码)

from 模块文件名 import 模块名

        只是导入相对应的模块,不是所有代码

from 模块文件名 import 模块名 as 别名

  (要是导入的模块名跟文件中的函数名字有相同的可以起个别名,python程序的运行时逐行解释的,相同的 后面会覆盖前面的)

导入模块的本质就是把python文件执行一遍。

3、random、string模块

 1 import random,string    
 2 print(random.random())#随机浮点数,默认取0-1,不能指定范围
 3 print(random.randint(1,20))#随机整数,顾头顾尾
 4 print(random.randrange(1,20))#随机产生一个range
 5 print(random.choice('x23serw4'))#随机取一个元素
 6 print(random.sample('hello',2))#从序列中随机取几个元素
 7 print(random.uniform(1,9))#随机取浮点数,可以指定范围
 8 x = [1,2,3,4,6,7]
 9 random.shuffle(x)#洗牌,打乱顺序,会改变原list的值
10 print(x)
11 print(string.ascii_letters+string.digits)#所有的数字和字母

4、time和datetime模块

时间有两种格式:1).时间戳 从unix元年到现在过了多少秒  2).格式化好的时间

1)、time模块

import time
print(time.time())#获取当前时间戳
time.sleep(10)#时间停留多少秒
today=time.strftime('%Y-%m-%d %H:%M:%S')#格式化时间格式
print(today)

#以上结果打印是:
1526614333.0762012 #时间戳
2018-05-18 11:32:13 格式化好的当前时间
time.gmtime()#默认取的是标准时区的时间
time.localtime()#默认取的是当前时区的时间
s=time.localtime(1514198608)
time.strftime('%Y-%m-%d %H:%M:%S',s) #1.时间戳转成时间元组 time.localtime 2.再把时间元组转成格式化的时间

2)、datetime模块

import datetime
print(datetime.datetime.today())  #获取当前时间,精确到秒
print(datetime.date.today()) #精确到天
res=datetime.date.today()+datetime.timedelta(days=-5) #当前时间的五天前
res1=datetime.date.today()+datetime.timedelta(days=5) #当前时间的五天后
res2=datetime.datetime.today()+datetime.timedelta(minutes=-5) #当前时间的五分钟前
print(res)
print(res1)
print(res2)

#以上结果是:
2018-05-18 11:41:46.661008 #获取当前时间,精确到秒
2018-05-18#精确到天
2018-05-13#当前时间的五天前
2018-05-23#当前时间的五天后
2018-05-18 11:36:46.661008 #当前时间的五分钟前

5、hashlib加密模块

  md5加密是不可逆的

import hashlib
m=hashlib.md5()#实例化加密对象
password='xuezhiqian'
print(password.encode())#把字符串转换成bytes类型
m.update(password.encode())#不能直接对字符串加密,需要将字符串转成二进制,也就是bytes类型
print(m.hexdigest())##返回加密后的十六进制结果

#以上结果是:
b'xuezhiqian'#bytes类型
18f1fc8d1614da0d26fbe8640805c046 #加密后的十六进制结果

 6、练习:(1)定义一个加密函数

1 def my_md5(str):
2     import hashlib
3     new_str=str.encode()#把字符串转成bytes类型
4     m=hashlib.md5()#实例化md5对象
5     m.update(new_str)#加密
6     return m.hexdigest()#获取返回结果

7、os模块

mport os
print(os.getcwd())#获取当前工作目录
print(os.chdir())#更改当前路径
print(os.mkdir('zll/huangrong'))#创建文件夹
print(os.makedirs('nhy/pyhton'))#创建递归文件,创建文件夹的时候,如果父目录不存在会自动帮你创建父目录
print(os.remove())#只能删除文件
print(os.rmdir())#删除指定的文件夹,只能删除空目录
print(os.listdir('e:\'))#列出一个目录下所有的文件。
print(os.getcwd())  # 取当前工作目录
os.chmod("/usr/local", 7)  # 给文件/目录加权限
print(os.chdir("../"))  # 更改当前目录
print(os.curdir)  # 当前目录
print(os.pardir)  # 父目录
print(os.makedirs("/usr/hehe/hehe1"))  # 递归创建文件夹,父目录不存在时创建父目录
print(os.removedirs("/usr/hehe/hehe1"))  # 递归删除空目录
print(os.mkdir("test1"))  # 创建文件夹
print(os.rmdir("test1"))  # 删除指定的文件夹
print(os.remove("test"))  # 删除文件
print(os.listdir('.'))  # 列出一个目录下的所有文件
os.rename("test", "test1")  # 重命名
print(os.stat("len_os.py"))  # 获取文件信息
print(os.sep)  # 当前操作系统的路径分隔符
#day5+os.sep+x.py
print(os.linesep)  # 当前操作系统的换行符
print(os.pathsep)  # 当前系统的环境变量中每个路径的分隔符,linux是:,windows是;
print(os.environ)  # 当前系统的环境变量
print(os.name)  # 当前系统名称,windos 系统是nt,
res=os.system('ipconfig')#执行操作系统命令的
print(res)
res=os.popen('ipconfig').read()
print(res)
__file__#获取当前文件的绝对路径
print(__file__)
print(os.path.abspath(__file__))  # 获取绝对路径
print(os.path.split("/usr/hehe/hehe.txt"))  # 分割路径和文件名
print(os.path.dirname("/usr/local"))  # 获取父目录,获取它的上一级目录
print(os.path.basename("/usr/local"))  # 获取最后一级,如果是文件显示文件名,如果是目录显示目录名
print(os.path.exists("/usr/local"))  # 目录/文件是否存在
print(os.path.isabs("."))  # 判断是否是绝对路径
print(os.path.isfile("xiaohei.py"))  # 判断是否是一个文件,:1.文件要存在2.必须是一个文件
print(os.path.isdir("/usr/local"))  # 是否是一个路径,目录是否存在
size=os.path.getsize('x.py')#获取文件的大小
print(os.path.join("root", 'hehe', 'a.sql','mysql'))  # 拼接成一个路径
print(os.path.getatime("len_os.py"))  # 输出最近访问时间
print(os.path.getmtime("len_os.py"))  # 输出最近访问时间
for abs_path,dir,file in os.walk('D:pypylianxiday6'):
    print(abs_path,dir,file)
    #abs_path 当前循环的绝对路径
    #dir 目录下面的文件夹
    #file 目录下面所有的文件

8、sys模块

import sys
print(sys.platform)#判断操作系统
print(sys.path)#python的环境变量
sys.path.append(r'D:pypylianxiday5')#增加变量
sys.path.insert(0,r'D:pypylianxiday5')#增加环境变量

9、练习(2)定义一个时间戳转成时间元组的函数:

def timestamp_to_fomat(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
        if timestamp:
        time_tuple=time.localtime(timestamp)
        res=time.strftime(format,time_tuple)#转换时间
    else:
        res=time.strftime(format)  #默认取当前时间
    return res

10、练习(3)定义一个把时间元组转换成时间戳的函数:

1 def strToTimestamp(str=None,format='%Y-%m-%d %H:%M:%S'):
2     if str:#如果传了时间的话
3         tp=time.strptime(str,format)  #转成时间元组
4         res=time.mktime(tp)  #再转成时间戳
5     else:
6         res=time.time()  #默认取当前时间戳
7     return  int(res)

11、练习(4)使用random模块随机生成双色球:

import random
def swq(num):
    f = open('shuangseqiu.txt', 'w+', encoding='utf-8')
    for i in range(num):
        nums = []
        bule_ball=str(random.randint(1,16))
        bule_ball=bule_ball.zfill(2)#篮球不够两位补零
        red_balles=random.sample(range(1,34),6)
        for j in red_balles:
            nums.append(str(j).zfill(2))#红球不够两位补零
        result='蓝色球:'+bule_ball+' 红色球:'+' '.join(nums)#.join将生成的list转为字符串
        f.write(result+'
')#将生成的号码写入文件

swq(10) #调用函数生成10组双色球
原文地址:https://www.cnblogs.com/xiehong/p/9055593.html