Python 模块

模块

模块

模块,在Python可理解为对应于一个文件。在创建了一个脚本文件后,定义了某些函数和变量。你在其他需要这些功能的文件中,导入这模块,就可重用这些函数和变量。 

模块分为

python 内置模块

第三方模块

自定义模块

为什么要使用模块

1、思路清晰

2、防止代码再次重写

模块导入方式

import 模块名 # 导入整个模块

import *  # 导入所有方法

from 模块名 import 方法  #导入单个方法

 通常包总是一个目录,可以使用import导入包,或者from + import来导入包中的部分模块。包目录下为首的一个文件便是 __init__.py。然后是一些模块文件和子目录,假如子目录中也有 __init__.py 那么它就是这个包的子包了。

字符串模块导入

__import__

__import__('test')


# __import__只能导入同一目录的文件
View Code

importlib

# importlib 是python提供的一个模块,这个可以导入不同穆勒的文件


import importlib
importlib.import_module('T.test')
View Code

time(时间)

import time

# time()
# 以秒的形式返回从1970年到现在的时间戳
print(time.time()) # 1556454391.3264115


# sleep()
# 休眠
time.sleep(1)


# gmtime()
# UTC时间,返回结构化时间
print(time.gmtime()) # time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=12, tm_min=26, tm_sec=32, tm_wday=6, tm_yday=118, tm_isdst=0)


# localtime()
# 取本地时间,返回结构化时间
print(time.localtime()) # time.struct_time(tm_year=2019, tm_mon=4, tm_mday=28, tm_hour=20, tm_min=26, tm_sec=32, tm_wday=6, tm_yday=118, tm_isdst=0)


# strftime()
# 格式化时间
now_time = (time.strftime("%Y-%m-%d %H:%M:%S"))
print(now_time) # 2019-04-28 20:26:32


# strptime()
# 转结构化
value = (time.strptime(now_time,"%Y-%m-%d %H:%M:%S"))
# 结构化,可以取不同的值
print(value.tm_year) # 2019 
print(value.tm_mon) # 4
print(value.tm_mday) # 28


# ctime()
# 固定格式
print(time.ctime()) # Sun Apr 28 20:26:32 2019


# maktime()
# 把结构化时间,转时间戳
print(time.mktime(value)) # 1556454392.0
View Code

random(随机数)

import random

# random()
# 随即生成一个 浮点数
number = random.random()
print(number) # 0.5773976675875958


# randint(a,b)
# 随即生成一个 a-b 之间的整数,这个数包括a,b
number = random.randint(0,9)
print(number) # 0


# randrange()
# 他不会包括后面的数
number = random.randrange(9)
print(number) # 8


# choice()
# 随即选取一个
num = [1,"two",3,"four",5]
print(random.choice(num)) # 1
print(random.choices(num)) # [3]


# sample()
# 根据要求的个数,随即打乱序列
print(random.sample(num,3)) # [5, 'four', 'two']
print(random.sample(num,len(num))) # [3, 'four', 'two', 1, 5]
View Code

os(文件)

import os

os.getcwd() # 获取当前工作目录
os.chdir("D:os") # 改变当前脚本工作目录
os.curdir # 返回当前目录 .
os.pardir # 获取当前目录的父目录 ..
os.makedirs(r".aab") # 创建多层目录
os.removedirs(r".aab") # 删除多层空目录
os.mkdir("aa") # 创建单层目录
os.rmdir("aa") # 删除单层空目录
os.listdir("path") # 当前路径所有文件及子目录的信息
os.remove("file") # 删除一个文件
os.rename("file","file.txt") # 重命名文件或目录
os.stat("path") # 获取文件或文件夹的详细信息


os.sep # 获取当前系统的路径分隔符,如 win: linux:/
os.linesep # 输出当前平台使用的终止符 如 win:
 linux:
 mac:

os.pathsep # 分割文件路径的字符串
os.name # 输出当前使用平台 如 win:nt linux:posix
os.system("dir") # 运行shell命令,直接显示
os.environ # 获取系统环境变量


os.path.abspath("path") # 返回绝对路径
os.path.split("path") # 将path分割成目录和文件名
os.path.dirname("path") # 返回目录,也就是返回split元祖中前面的一个元素
os.path.basename("path") # 返回最后的文件名
os.path.exists("path") # 当前目录是否存在,True or False
os.path.isabs("path") # 是不是绝对路径
os.path.isfile("path") # 是不是文件
os.path.isdir("path") # 是不是目录
os.path.join("path1,path2") # 目录拼接
os.path.getatime("path") # 返回文件或目录最后存取时间
os.path.getmtime("path") # 返回文件或目录最后修改时间
View Code 

shutil

import shutil

# 复制文件
shutil.copyfile(old_file,new_file)

# 复制目录
shutil.copytree(old_dir,new_dir)
View Code

sys(系统)

import sys

sys.argv # 命令行参数List,第一个元素是程序本身路径,如win cmd下 python file.py post
sys.path # 返回模块搜索路径,初始化时使用PYTHONPATH 环境变量的值
sys.platform # 返回操作系统平台名称

sys.exit() # 退出程序
sys.version # 获取python解释程序的版本信息
sys.stdout.write("please:")
View Code

subprocess 

import subprocess

# 操作cmd , 命令:dir 解释器:cmd
# 第一种
result = subprocess.getoutput('dir')
print(result)
# 第二种
# 执行stdout=subprocess.PIPE时,将子进程转主进程,也就是转为一个对象
obj = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE,universal_newlines=True)
# 调用
print(obj.stdout.read())
View Code

hashlib(加密)

import hashlib

m = hashlib.md5() # 生成一个md5加密变量
m.update("Hello world".encode("utf-8")) # 进行加密
print(m.hexdigest()) # 查看密文 ,3e25960a79dbc69b674cd4ec67a72c62


s = hashlib.sha256() # 生成一个sha256加密变量
s.update("Hello world".encode("utf-8")) # 进行加密
print(s.hexdigest()) # 查看密文 , 64ec88ca00b268e5ba1a35678a1b5316d212f4f366b2477232534a8aeca37f3c
View Code

logging(日志)

日志格式,日志级别

import logging

# 默认从 warning 级别开始显示
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")

# 输出
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message



# 修改默认级别显示
logging.basicConfig(level=logging.DEBUG)
logging.debug("debug message")
logging.info("info message")
logging.warning("warning message")
logging.error("error message")
logging.critical("critical message")

# 输出
DEBUG:root:debug message
INFO:root:info message
WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message



# 修改更多信息
logging.basicConfig(level=logging.DEBUG,
                    format='[line:%(lineno)d] %(asctime)s %(filename)s %(levelname)s %(message)s',# 存储信息
                    datefmt="%Y-%m-%d %X", # 时间格式
                    filename="log.txt", # 文件名字
                    filemode="a") # 文件模式
logging.info("info message")



format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s用户输出的消息
View Code

日志,控制台同时输出

import logging

log = logging.getLogger() # 创建
fh = logging.FileHandler("log.txt") # 用于写入日志
sh = logging.StreamHandler() # 用于输出控制台

formatter = logging.Formatter("%(asctime)s -- %(levelname)s:%(message)s",datefmt="%Y-%m-%d %X") # 输出格式操作
fh.setFormatter(formatter) # formatter格式
sh.setFormatter(formatter) # 同上

log.addHandler(fh) # 添加到log对象中
log.addHandler(sh) # 同上

log.setLevel(logging.DEBUG) # 设置级别
log.info("Hello world!")
View Code

configparser(读取配置文件)

import configparser
# 创建对象
config = configparser.ConfigParser()

# 创建值
config["DEFAULT"] = {"teacher":"kidd"} # DEFAULT 是默认的值
config["Class one"] = {1:"小明",
                       2:"小红"}
config["Class two"] = {1:"小李",
                       2:"小军"}


# 写入
with open("demo.txt",'w',encoding="utf-8") as f:
    config.write(f)


# 读取
print(config["DEFAULT"]["teacher"]) # kidd
config.read("demo.txt")
print(config.sections()) # 产看所有项,除默认项,['Class one', 'Class two']
print(config.defaults()) # 产看默认项,OrderedDict([('teacher', 'kidd')])
print(config["DEFAULT"]["teacher"]) # kidd


# 删除
config.remove_option("Class one","1") # 删除一个键值对
config.remove_section("Class one") # 删除整个块
config.write(open("demo.txt",'w')) # 因为不能修改,所以重新创建并写入


# 修改
config.set("Class two","1","小强") # set(group,key,value)
config.write(open("demo.txt",'w',encoding="utf-8"))
View Code

re(匹配)

匹配规则

元字符
. #匹配任意字符,除换行符
^ #匹配一行字符串的开头
$ #匹配一行字符串的结尾
* #匹配0个或多个表达式
+ #匹配1个或多个表达式
? #匹配0个或1个前面的正则表达式定义的片段
{n} #精准匹配前面表达式
{n,m} #匹配n到m次
[...] #用来表示一组字符,单独列出,可以看做or,比如[a,s,d],匹配a、s或d
[^...] #不在[ #]中的字符,比如[^a,s,d],匹配除了a,s,d之外的字符
( ) #匹配括号内的表达式, # #给组定义名称 # #(?P<id>),<>里面填写名称,<名称>后面跟匹配规则
a | b #匹配a或b

反斜杠后边跟元字符,去除特异功能
反斜杠后边跟普通字符,实现特殊功能

的用法
d #匹配任意数字,相当于[0-9]
D #匹配任意非数字,相当于[^0-9]
s #匹配任意空白字符,相当于[	

fv]
S #匹配任意非空白字符,相当于[^	

fv]
w #匹配字母数字下划线,相当于[a-zA-z/d_]
W #匹配不是字母数字下划线,相当于[a-zA-z/d_]
A #匹配字符串的开头,同^
 #匹配字符串的结尾,同$
 #匹配一个特殊边界字符

 #匹配换行符
	 #匹配制表符


修饰符
re.I #使匹配对大小写不敏感
re.L #做本地化识别(locale-aware)匹配
re.M #多行匹配,影响^和$
re.S #使.匹配包括换行在内的所有字符
re.U #根据unicode字符集解析字符。影响w,W,,B
re.X #该标志通过给予你更灵活的格式以便你将正则表达式写得更易于理解
View Code

方法

import re

# match() 从字符串开头开始匹配
content = "Hi,Hello,Hi"
ret = re.match(".*?[i,o]",content)
print(ret) # <_sre.SRE_Match object; span=(0, 2), match='Hi'>
print(ret.group()) # Hi
print(ret.span()) # (0, 2)
# 匹配失败,因为是从头开始匹配
ret = re.match("Hello",content)
print(ret) # None


# search() 返回第一个符合条件的匹配目标
content = "Hi,Hello,Hi"
ret = re.search(".*?[i,o]",content)
print(ret) # <_sre.SRE_Match object; span=(0, 2), match='Hi'>
print(ret.group()) # Hi
print(ret.span()) # (0, 2)


# findall() 返回所有符合条件的匹配目标
content = "Hi,Hello,Hi"
ret = re.findall(".+?[i,o]",content)
print(ret) # ['Hi', ',Hello', ',Hi']


# sub() 替换
content = "Hello1234 world3424"
sub = re.sub('d','',content)
print(sub) # Hello world


# split() 分割
content = "Helloa bworld"
ret = re.split("a.*b",content)
print(ret) # ['Hello', 'world']


# compile() 将正则字符串变编译成正则表达式对象
content = re.compile("H.*")
ret1 = content.findall("Hi")
ret2 = content.findall("Hello")
print(ret1) # ['Hi']
print(ret2) # ['Hello']
View Code

命名

import re
s = "Hello World!"
reg = re.search("(?P<language>w+s+w+)", s)
print(reg.groupdict()["language"])
View Code

json(格式化数据)

import json
f = open("json_txt","r+")
content = {"name":"kidd"}
# 写入
f.write(json.dumps(content))
f.flush()

# 读取
json.loads(f.read())
View Code

pickle

# 与json用法一致,但pickle数据不能可视化

import pickle
f = open("pickle_txt","rb+")
content = {"name":"kidd"}
#写入
f.write(pickle.dumps(content))
#读取
pickle.loads(f.read())
View Code

shelve

# shelve不可视化

import shelve
f = shelve.open("test")
f["name"] = "kidd"
# 取值与字典一致
content = f.get("name")
print(content)
View Code

xml

数据

<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
View Code

操作

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root.tag)
 
#遍历xml文档
for child in root:
    print(child.tag, child.attrib)
    for i in child:
        print(i.tag,i.text)
 
#只遍历year 节点
for node in root.iter('year'):
    print(node.tag,node.text)
#---------------------------------------

import xml.etree.ElementTree as ET
 
tree = ET.parse("xmltest.xml")
root = tree.getroot()
 
#修改
for node in root.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated","yes")
 
tree.write("xmltest.xml")
 
 
#删除node
for country in root.findall('country'):
   rank = int(country.find('rank').text)
   if rank > 50:
     root.remove(country)
 
tree.write('output.xml')
View Code
import xml.etree.ElementTree as ET
 
 
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
 
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
 
ET.dump(new_xml) #打印生成的格式
View Code
原文地址:https://www.cnblogs.com/py-peng/p/10786364.html