本节大纲:

  1. 模块介绍
  2. time &datetime模块
  3. random
  4. os
  5. sys
  6. shutil
  7. json & picle
  8. shelve
  9. configparser
  10. hashlib

一、模块介绍

  模块的定义:在python中一个.py文件我们就可以称之为一个模块,python中有很多自带的模块我们叫内置模块,而我们自己创建的模块称之为自定义模块。模块可以被别的程序引入,以使用该模块中的函数等功能

  模块的导入:

# 方法一:
# import time
# 方法二:
from time import time
a = time()
print(a)
'''
以上两者的区别是:
第一种方法的导入的是模块的全部内容
第二种导入的是模块的其中一方法或属性
'''

所以在导入模块的时候需要根据需要来导入相应的内容,如果只用到模块内的其中一方法或属性尽量选择第二种导入方式,而需要用多个的时候为了减少代码量就选择第一种方式。当然import后面可以跟多个模块名。

二、time和datetime模块

在学习time模块之前我们学习一下time的一些属性。

索引(Index) 属性(Attribute) 值(Values)
0 tm_year(年) 比如2011
1 tm_mon(月) 1 - 12
2 tm_mday(日) 1 - 31
3 tm_hour(时) 0 - 23
4 tm_min(分) 0 - 59
5 tm_sec(秒) 0 - 61
6 tm_wday(weekday) 0 - 6(0表示周日)
7 tm_yday(一年中的第几天) 1 - 366
8 tm_isdst(是否是夏令时) 默认为-1

time模块

 import time

 #时间戳
print(time.time()) #返回当前时间的时间戳 #元组的形式
print(time.gmtime())#返回格林威治0时区的时间
# time.struct_time(tm_year=2018, tm_mon=4, tm_mday=17, tm_hour=15,
# tm_min=34, tm_sec=6, tm_wday=1, tm_yday=107, tm_isdst=0)
print(time.gmtime().tm_year) #可以根据元素的关系取出对应的时间
print(time.localtime()) #也是元组的形式 #将元组形式转换成时间戳 now = time.localtime()
print(time.mktime(now)) #将元组形式转换成指定的字符串格式 now1 = time.localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S',now1)) #将自定义的字符串格式转换为元组的形式 print(time.strptime('2016-07-08','%Y-%m-%d')) time.sleep(2) #睡两秒 m = time.time() #当前时间的时间戳
n = time.gmtime() #返回的是时间的元组形式,传入时间戳参数可以将时间戳转换成元组
n1 = time.gmtime().tm_year #可以通过对应的元素来取得对应的时间信息
l = time.localtime() #返回当前本地时间的元组形式,将时间搓传入
l1 = time.localtime(m) #传入参数也可以返回对应时间的元组形式
c = time.mktime(n) #将元组转换为时间戳
s = time.strftime("%Y-%m-%d %H-%M-%S") #以一定的格式输出时间
s2 = time.strftime("%Y-%m-%d %H-%M-%S",n) #后面如果接参数则必须是元组的形式
p = time.strptime("2018-03-01","%Y-%m-%d") #将时间转换成元组的形式
print(s2)

datetime

 import datetime

 # print(datetime.datetime.today()) 默认返回当前日期和时间的对象,也可以自定义日期和时间
# print(datetime.date.today()) 默认返回当前日期的对象,也可以自定义日期 # print(datetime.datetime.now()) 返回当前时间 today = datetime.datetime.today()
print(today) print(today.strftime("%I:%M:%S %p %d/%m/%Y")) #自定义格式化时间
print(today.timetuple()) #将时间转换成元组的形势
print(today.replace(1949,10,1)) #返回一个替换后的date对象 yesterday = today - datetime.timedelta(days=1) #对(days)天,(hours)小时,(minutes)分进行运算
print(yesterday)

random模块

 import random

 print(random.random())  #生成一个0-1 的随机数
print(random.randint(1,7)) #s生成一个指定范围的的随机整数,两边都是闭区间
print(random.randrange(1,3)) #生成一个指定范围的随机整数,左闭右开

下面是一个random的简单应用:

 '''
这是一个生成随机验证码的简单程序
'''
import random
checkcode=''
for i in range(6):
current = random.randint(1,6)
if i == current: #若两个数相等,用ASII返回一个字母
temp = chr(random.randint(65,90))
else: #若不相等返回数字,并转换为字符串
temp = random.randint(1,9)
checkcode += str(temp) #字符串拼接
print(checkcode)

os模块

 import os

 print(os.getcwd()) #获取当前的工作目录
#os.chdir('dirname')改变当前脚本的工作目录,相当于shell的cd
print(os.curdir) #返回当前目录
print(os.pardir) #返回当前目录的父目录字符串名
#os.makedirs('a/b/c') #可以生成多层递归目录
#os.removedirs(r'G:\PythonLearning\oldboy\oldboynotes\fiveday\osmodle\a\b\c')
#若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
#os.mkdir('a') #生成单级目录
#os.rmdir(r'G:\PythonLearning\oldboy\oldboynotes\fiveday\osmodle\a')
#删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdirdirname
#print(os.listdir(r'G:\PythonLearning\oldboy\oldboynotes\fiveday\osmodle\a'))
#列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
#os.remove(r'G:\PythonLearning\oldboy\oldboynotes\fiveday\osmodle\a\1')
#删除指定的文件
#os.rename('oldname','newname') 重命名文件/目录
#print(os.stat('G:')) 获取文件或目录的信息
#print(os.sep) 输出操作系统指定的路径分隔符
# print(os.linesep) 输出当前平台使用的行终止符,即换行符
# print(os.pathsep) 输出用于分割文件路径的字符串,一般为;
# print(os.name) 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
#print(os.environ) #获取系统的环境变量
#print(os.path.abspath(__file__)) #返回path规范化的绝对路径
#print(os.path.split(__file__)) #将path分割成目录和文件名二元组返回
#print(os.path.dirname(__file__)) #返回path的目录。其实就是os.path.split(path)的第一个元素
#print(os.path.basename(__file__)) #返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
#print(os.path.exists(__file__)) #如果path存在,返回True;如果path不存在,返回False
# os.path.isabs(path) #如果path是绝对路径,返回True
# os.path.isfile(path) #如果path是一个存在的文件,返回True。否则返回False
# os.path.isdir(path) #如果path是一个存在的目录,则返回True。否则返回False
# os.path.join(path1[, path2[, ...]]) #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
# os.path.getatime(path) #返回path所指向的文件或者目录的最后存取时间
# os.path.getmtime(path) #返回path所指向的文件或者目录的最后修改时间

sys模块

 import sys
print(sys.path) #打印环境变量,返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 #sys.path.append() 将以路径添加至环境变量
#print(sys.argv) 打印程序本身的路径
'''sys.exit()
print('a')''' #sys.exit()表示正常退出程序,正常退出后,后面不运行 #print(sys.version) 获取解释器的版本值
#print(sys.platform) #返回操作系统平台名称
# sys.stdout.write('please')
# sys.stdout.write('you') 标准输出,不换行

json和picle模块

json:用于字符串和python数据类型直接转换

picle:用于python特有的类型和python的数据类型转换

json和picle的方法和用法一致只不过功能稍微不同:dump,load,dumps,loads

 import json

 di={"json":1,"picle":2}
js = json.dumps(di) #dumps将python的数据类型转换为所有语言都识别的字符串
print(type(js))
with open("a.txt","w") as fp:
json.dump(di,fp) #dump则是将python的数据类型转换为所有语言都识别的字符串,并且必须写入文件
print(js) import pickle pi = pickle.dumps(di) #dumps将python的数据类型转换为所有语言都识别的二进制字符串模式
print(type(pi)) with open("b.txt","w") as fp2:
pickle.dump(pi,fp2) #dump则是将python的数据类型转换为所有语言都识别的二进制字符串,必须写入文件
print(pi)

反序列化操作

 f = open("a.txt","r")
a = f.read() #直接读取内容
print(json.loads(a)["json"]) #然后对其反序列化操作
f2 = open("a.txt","r")
print(json.load(f2)) #对文件描述符进行反序列化操作

shutil和zipfile模块

 import shutil

 #f = open('a',encoding='utf-8')
# f.write('这一个关于复制的模块')
# f2 = open('b','w',encoding='utf-8')
# shutil.copyfileobj(f,f2) #对文件里的内容进行拷贝,文件对象
# shutil.copyfile('a','c') #直接对文件进行拷贝,文件名
# shutil.copystat('b','c') #拷贝状态的信息,包括:mode bits, atime, mtime, flags
# #shutil.copytree('timemodle','d') #递归的去拷贝文件
#hutil.rmtree('d') #递归删除文件
#shutil.move() #递归移动文件
#shutil.make_archive('shutilmodle','zip',r'G:\PythonLearning') #对文件进行压缩 import zipfile z = zipfile.ZipFile('a.zip','w') #压缩
z.write('a')
print('---')
z.write('b')
z.close() z = zipfile.ZipFile('a.zip','r') #解压
z.extractall()
z.close()

shelve模块

 #shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,
# 可以持久化任何pickle可支持的python数据格式,字典,列表,类等
import shelve,datetime d = shelve.open('shelvet') info = {'age':22,'job':'it'}
name = ['wallace','alex']
date = datetime.date.today() d['info']=info
d['name'] = name
d['date'] = date
print(d.get('info'))
d.close()

configparser模块

该模块用于生成和修改配置文件

 import configparser

 config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '',
'Compression': 'yes',
'CompressionLevel': ''} config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)

获取文档内的内容

 >>> import configparser
>>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
''
>>> for key in config['bitbucket.org']: print(key)
...
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'

修改文档

 [section1]
k1 = v1
k2:v2 [section2]
k1 = v1 import ConfigParser config = ConfigParser.ConfigParser()
config.read('i.cfg') # ########## 读 ##########
#secs = config.sections()
#print secs
#options = config.options('group2')
#print options #item_list = config.items('group2')
#print item_list #val = config.get('group1','key')
#val = config.getint('group1','key') # ########## 改写 ##########
#sec = config.remove_section('group1')
#config.write(open('i.cfg', "w")) #sec = config.has_section('wupeiqi')
#sec = config.add_section('wupeiqi')
#config.write(open('i.cfg', "w")) #config.set('group2','k1',11111)
#config.write(open('i.cfg', "w")) #config.remove_option('group2','age')
#config.write(open('i.cfg', "w"))

hashlib模块

该模块主要用于对文档内容进行加密计算

 import hashlib

 '''md5,SHA1, SHA224, SHA256, SHA384, SHA512
不同的算法加密程度不同''' m = hashlib.sha512()
m.update(b'hello')
m.update('汪冠涛'.encode('utf-8')) #中文时必须先对其转码为unicode
print(m.digest())
m.update(b"it's be long time since last time...")
print(m.digest())
print(m.hexdigest())
 b'i\xa4D\xf9\xa2\xc2\xb3}\x97U\xa9\xfc9\xcf_\xff}\xf1Ubq\xb4\xcb\xf9u\xed4I\xf6\xb23\x17\xcb\x93cjH[VP\x04\xe9)\x11\x1c\x06\xa0\xcc\xadN\xafd\xc7\xf4\rP\xd0\xbd\x93\xa98z\x84\xad'
b'\xbc\xe0\x94\xf5\x82\xa0i\x00\x03\xbd\xd5\xdf\xa0~\xd1\xd0\x1bD5\xdaJ_\x12\xcb>\xf9H7)\x1f\xe5\xb8\xf5\xb4\x96\x9d\xb5\x1c\x15Z\xcc7\xc9\x1c\xd8\xdd\x92\x89\xb2\x92A\x143\x01XR\xbb\x1a\xc5\xf8\xa2>d\xe2'
bce094f582a0690003bdd5dfa07ed1d01b4435da4a5f12cb3ef94837291fe5b8f5b4969db51c155acc37c91cd8dd9289b292411433015852bb1ac5f8a23e64e2

Python 全栈开发六 常用模块学习的更多相关文章

  1. Python全栈开发-Day5-常用模块学习

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil shelve xml处理 pyyaml处理 configparser hashlib re正则 ...

  2. Python全栈之路----常用模块学习----模块的种类和导入方法

    什么是模块? 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码 ...

  3. Python全栈之路----常用模块----hashlib加密模块

    加密算法介绍 HASH       Python全栈之路----hash函数 Hash,一般翻译做“散列”,也有直接音译为”哈希”的,就是把任意长度的输入(又叫做预映射,pre-image),通过散列 ...

  4. python全栈开发day22-常用模块二(hashlib、configparse、logging)

    一.昨日内容回顾 1.钻石继承 #新式类,本身或父类显示继承object #找名字的时候是广度优先顺序 #有mro方法,super方法, # super并不是单纯的找父类,和mro顺序是完全对应的 # ...

  5. python全栈开发day17-常用模块collections,random,time,os,sys,序列化(json pickle shelve)

    1.昨日内容回顾 1.正则表达式     # 正则表达式 —— str           # 检测字符串是否符合要求     # 从大段的文字中找到符合要求的内容 1).元字符 #. # 匹配除换行 ...

  6. Python全栈之路----常用模块----subprocess模块

    我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的模块在python ...

  7. Python全栈之路----常用模块----软件开发目录规范

    目录基本内容 log  #日志目录 conf  #配置目录 core/luffycity  #程序核心代码目录  #luffycity 是项目名,建议用小写 libs/modules  #内置模块 d ...

  8. Python 全栈开发九 日志模块

    日志是一种可以追踪某些软件运行时所发生事件的方法.软件开发人员可以向他们的代码中调用日志记录相关的方法来表明发生了某些事情.一个事件可以用一个可包含可选变量数据的消息来描述.此外,事件也有重要性的概念 ...

  9. Python全栈之路----常用模块----re 模块

    正则表达式就是字符串的匹配规则,在多数编程语言里都有相应的支持,python里对应的模块是 re. re的匹配语法有以下几种 re.match 从头开始匹配 re.search 匹配包含 re.fin ...

随机推荐

  1. day_6.14py网络编程

    被动套接字和新建出套接字的区别 单任务,单线程,非阻塞!!!!服务器! #2018-6-14 16:51:25 #!--*--coding:utf-8 --*-- ''' 单进程,单任务 少的可以,多 ...

  2. SPL标准库-数据结构

    数据结构:栈 );] = ;] = ;var_dump($array); 来自为知笔记(Wiz)

  3. 《Thinkphp5使用Socket服务》 入门篇

    上车啦!!! 今天来说一下thinkphp5.0下使用wokerman的socket服务. 安装: composer的安装方法,Windows下直接下个composer的应用程序,双击安装,环境变量同 ...

  4. 【react】---context的基本使用新版---【巷子】

    一.全局定义context对象 globalContext.js import React from "react"; const GlobalContext = React.cr ...

  5. Javascript合并表格相同内容单元格示例

    效果图: HTML代码: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http: ...

  6. css学习_css写的位置

    !!!拿到一个页面后应该先写结构再写样式 结构由大到小,由外到里 样式最好按顺序加 position  .float . 颜色  背景  字体 等... 1.行内(内联)样式 2.内部样式表(按道理可 ...

  7. 阿里云容器服务与ASP.NET Core部署:用 docker secrets 保存 appsettings.Production.json

    这是我们使用阿里云容器服务基于 docker 容器部署 asp.net core 应用遇到的另一个问题 —— 如果将包含敏感信息的应用配置文件 appsettings.Production.json ...

  8. You are using pip version 9.0.1, however version 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command.

    实测使用pip3进行一些软件安装的时候,会弹出这个,记住不要理会,一旦你执行,就会升级pip,并冲突pip3造成pip3不能用,这时候就要重新安装一下python3

  9. PHP利用反射根据类名反向寻找类所在文件

    有时候分析源码时,会被博大精深的层层代码搞得晕头转向,不知道类是定义在哪个文件里的,有时候IDE所提供的方法声明未必准确.在这种情况下,我们可以利用反射找到类所在的文件. 在你发现实例化类的地方(例如 ...

  10. 【插头dp】 hdu4285 找bug

    打模板的经验: 1.变量名取一样,换行也一样,不要宏定义 2.大小写,少写,大括号 #include<algorithm> #include<iostream> #includ ...