sys模块常用属性和方法:
sys提供对Python解释器相关的操作
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.path 返回模块的搜索路径,site-packages 存放第三方库的路径
sys.exit() 退出程序
sys.platform 返回系统类别,windows下返回win32
os模块常用属性和方法:
os提供系统级别的操作
os.mkdir(sys.argv[1]) 创建目录
os.mknod("test.log") 创建文件,windows 里面mknod会报错,linux不会
os.path.dirname(__file__) 获取当前文件的父级目录
os.path.basename(__file__) 获取当前文件的名字
os.path.join() 拼接路径地址
# \r 表示将光标的位置回退到本行的开头位置
# \b 表示将光标的位置回退一位
time模块常用属性和方法:
time.time()
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) 转换本地时间为固定格式
time.sleep(1) 暂停1秒
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time
import datetime
# print("start to sleep ...")
# time.sleep(2)
# print("wake up ...")
# 时间戳 1970.1.1 00:00:00 开始
print(time.time())
print(time.localtime())
# 当前系统时间
print(time.ctime())
# 24*60*60 = 1天 = 86400 秒
print(time.ctime(time.time() - 24 * 60 * 60))
# 将时间戳 转换为 UTC 的 struct_time 格式
print(time.gmtime(time.time() - 24 * 60 * 60 + 8 * 60 * 60))
# time_obj = time.gmtime(time.time() - 24 * 60 * 60 + 8 * 60 * 60)
# %s 占位符
# print("%s-%s-%s %s:%s:%s" % (time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday,
# time_obj.tm_hour, time_obj.tm_min, time_obj.tm_sec))
# print("%f"%(2))
# 返回本地时间 的struct time对象格式, 同上
print("localtime ",time.localtime())
print(time.localtime(time.time() - 86400))
# 与time.localtime()功能相反,将struct time对象格式转为时间戳
print(time.mktime(time.localtime()))
# 将struct_time 转为指定字符串
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 将字符串转换为struct_time格式
print(time.strptime("2018-01-08", "%Y-%m-%d"))
# datetime
# 当前日期
print(datetime.date.today())
# 将时间戳 转换为 日期
print("xxxx",datetime.date.fromtimestamp(time.time() - 86400))
# 当前时间
current_time = datetime.datetime.now()
print(current_time)
print(current_time.timetuple())
print(current_time.replace(2014,1,14))
str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M")
str_to_date = datetime.datetime.strftime(current_time, "%d/%m/%y %H:%M")
print("str_to_date ",str_to_date)
new_date = datetime.datetime.now() + datetime.timedelta(days=10)
print(new_date)
new_date = datetime.datetime.now() + datetime.timedelta(days=-10)
print(new_date)
new_date = datetime.datetime.now() + datetime.timedelta(hours=-10)
print(new_date)
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120)
print(new_date)
json模块常用属性和方法:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
# python里面的json.loads()解析的时候内部元素如果是字符串,必须是双引号
# dumps()转为字符串不用必须是双引号
s = '{"status":1000,"desc":"ivd"}'
l = "[11,22,33,44]"
# json.loads() 将字典,列表,元组形式的字符串转换为相应的字典,列表,元组
# => 转换为Python的基本数据类型
res = json.loads(s)
print(res, type(res))
res2 = json.loads(l)
print(res2, type(res2))
# json.dumps() 将Python的基本数据类型 转换为字符串类型
# dumps() 转为字符串不用必须是双引号
dic = {'k1':123,'k2':'v2'}
ret = json.dumps(dic)
print(ret, type(ret))
# 元组会转变为LIST类型,因为其他语言没有元组这个数据类型
n = (11,22,33,44,"alex")
s1 = json.dumps(n)
print(s1,type(s1))
s2 = json.loads(s1)
print(s2,type(s2))
pickle模块常用属性和方法:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pickle
import json
# json是可以在不同语言之间交换数据的,而pickle只在python之间使用。
# json只能序列化最基本的数据类型,而pickle可以序列化所有的数据类型,包括类,函数都可以序列化。
accounts = {
1000: {
"name": "Alex郭",
"email": "lijie@126.com",
"password": "abc123",
"balance": 15000,
"phone": 13344445555,
"bank_acc": {
"ICBC": 1432245,
"CBC": 3422552,
"ABC": 1235353
}
},
1001: {
"name": "Guolei",
"email": "Guolei@126.com",
"password": "abc12223",
"balance": -15000,
"phone": 13344445555,
"bank_acc": {
"ICBC": 2334556,
}
}
}
# 利用pickle模块将字典转换为字节
print(pickle.dumps(accounts))
# 利用json模块将字典序列化
# print(bytes(json.dumps(accounts),encoding="utf-8"))
with open("account.db", "wb") as f:
# pickle.dumps() 存储字节数据
f.write(pickle.dumps(accounts))
# f.write(bytes(json.dumps(accounts),encoding="utf-8"))
hashlib模块常用方法和属性:
# hashlib 加密模块
import hashlib
# 混淆加密
hash = hashlib.md5(bytes("xxx", encoding="utf-8"))
hash.update(bytes("password", encoding="utf-8"))
print(hash.hexdigest()) # 十六进制数据字符串值
print(hash.digest()) # 二进制数据字符串值
# 普通加密
hash = hashlib.md5() # md5对象,md5不能反解,但是加密是固定的,就是关系是一一对应,所以有缺陷,可以被对撞出来
hash.update(bytes('password', encoding='utf-8')) # 要对哪个字符串进行加密,就放这里
print(hash.hexdigest()) # 拿到加密字符串
configparse模块常用属性和方法:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import configparser
con = configparser.ConfigParser()
# con对象的read功能,打开文件读取文件,放进内容
con.read("ini", encoding="utf-8")
# con对象的sections,内存中寻找所有的【xxx】
result = con.sections()
print(result)
# con对象获取指定section下所有的key
ret = con.options("guolei")
print(ret)
# con对象获取指定section下指定key的value
age = con.getint("guolei", "age")
gender = con.get("guolei", "gender")
print(age, gender)
# 检查,检查section和key
s1 = con.has_section("guolei")
s2 = con.has_option("guolei", "age")
print(s1, s2)
# 添加节点
con.add_section("lixiaoning")
con.set("lixiaoning", "age", "31")
con.set("lixiaoning", "gender", "laji")
con.write(open("ini", "w"))
# 删除指定节点
# con.remove_section("lixiaoning")
# 删除指定节点指定的key
# con.remove_option("lixiaoning","age")
# con.write(open("ini","w"))
logging模块常用属性和方法:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import logging
# 方便,线程安全
# logging.basicConfig(filename="log.log",
# format="%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s",
# datefmt="%Y-%m-%d %H:%M:%S %p",
# level=logging.ERROR)
"""
日志级别:
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
"""
# logging.critical("ccccc")
# logging.fatal("fffff")
# logging.error("eeeee")
# logging.warning("wwwww")
# logging.info("iiiiii")
# logging.debug("ddddd")
#
# logging.log(logging.INFO,"2222")
# 多个文件
# 创建文件
file_1_1 = logging.FileHandler("l1_1.log","a")
# 创建格式
fmt = logging.Formatter(fmt="%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s")
# 应用文件格式
file_1_1.setFormatter(fmt)
file_1_2 = logging.FileHandler("l1_2.log","a")
fmt = logging.Formatter()
file_1_2.setFormatter(fmt)
# 定义日志
logger1 = logging.Logger("s1", level=logging.ERROR)
logger1.addHandler(file_1_1)
logger1.addHandler(file_1_2)
# 写日志
logger1.critical("eeee")
subprocess模块常用属性和方法:
https://www.cnblogs.com/yyds/p/7288916.html
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import subprocess
# 专门用于python执行系统命令
def ipconfig(self, data):
ipconfig_info = json.loads(data)
res = subprocess.run("ipconfig", shell=True, universal_newlines=True, stdout=subprocess.PIPE)
self.request.sendall(res.stdout.encode())
shutil模块常用属性和方法:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import shutil
# shutil 高级文件处理模块
# 将文件内容拷贝到另外一个文件中
# shutil.copyfileobj(open("old.xml", "r", encoding="utf-8"), open("new.xml", "w", encoding="utf-8"))
# 拷贝文件(所有)
# shutil.copyfile("f1.log","f2.log")
# 拷贝权限
# shutil.copymode("f1.log", "f2.log")
# 拷贝状态
# shutil.copystat("f1.log", "f2.log")
# 拷贝文件和权限
# shutil.copy("f1.log", "f2.log")
# 拷贝文件和状态信息
# shutil.copy2("f1.log", "f2.log")
# 递归拷贝文件和文件夹,ignore忽略
# shutil.copytree("folder1","folder2", ignore=shutil.ignore_patterns("*.pyc","tmp"))
# 递归删除
# shutil.rmtree("folder1")
# 重命名
# shutil.move("folder1","folder2")
# 压缩文件,将指定目录下的文件压缩到指定目录(默认当前目录)
# ret = shutil.make_archive("wwwwwww","gztar",root_dir="/Usrs/guolei/test")
# ret = shutil.make_archive("/Usrs/guolei/wwwwwww","gztar",root_dir="/Usrs/guolei/test")
import zipfile
# 给zip压缩包添加文件 w 和 a 都可以
# z = zipfile.ZipFile("test.zip", "w")
# z.write("old.xml")
# z.close()
# 解压文件
# z = zipfile.ZipFile("test.zip", "a")
# 获取压缩包内的文件名LIST
# r = z.namelist()
# print(r)
# 解压指定文件
# z.extract("old.xml",path="D:\\")
# 解压所有文件
# z.extractall(path="D:\\")
# z.close()
import tarfile
# 添加
# tar = tarfile.open("your.tar", "w")
# tar.add(r"D:\PyCharm_2018.2.4\PycharmProjects\MyLesson1\module3\new.xml",arcname="new.xml")
# 解压
tar = tarfile.open("your.tar", "r")
r = tar.getnames()
s = tar.getmembers()
print(r,s)
# tar.extractall("D:\\")
tar.close()
xml模块常用属性和方法:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
from xml.etree import ElementTree as ET
from xml.dom import minidom
# r = requests.get("http://www.webxml.com.cn//webservices/qqOnline"
# "WebService.asmx/qqCheckOnline?qqCode=378934585")
# print(r.url)
# result = r.text
# print(result)
#
# # 解析xml格式内容
# node = ET.XML(result)
# # node = ET.XML(s)
#
# # 获取内容
# if node.text == "Y":
# print("在线")
# else:
# print("离线")
"""
r = requests.get("http://www.webxml.com.cn//webservices/TrainTime"
"WebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=")
print(r.url)
result = r.text
print(result)
# 解析xml格式内容
node = ET.XML(result)
print(node.tag)
for item in node.iter("TrainDetailInfo"):
# print(item.tag, item.attrib)
print(item.find("TrainStation").text,item.find("ArriveTime").text,item.find("StartTime").text)
"""
# XML文件处理,只能读写不能保存
with open("first.xml", "r", encoding="utf-8") as f:
result = f.read()
print(result)
root = ET.XML(result)
print("root.tag: ", root.tag)
for node in root.findall("country"):
print(node.tag, node.attrib, node.find("name").text)
if node.find("people").text == "10000":
print("删除people=10000的")
# 不能直接删除从 for循环的对象里面删除,不然循环会出问题
root.remove(node)
else:
pass
# 【将root对象转换为tree对象即可使用ElementTree的write()方法进行保存】
tree = ET.ElementTree(root)
tree.write("first_1.xml", encoding="utf-8", xml_declaration=True)
# 另外一种处理方式,打开并解析文件内容,可读写 and 修改内容后可以保存
tree = ET.parse("first.xml")
root = tree.getroot()
print(dir(root))
# findall()查找data下所有的country子元素
for node in root.findall("country"):
new_people = int(node.find("people").text) + 1
if new_people > 15000:
node.find("people").text = str(new_people)
node.find("people").set("type", "num")
# 删除节点的属性
# del node.find("people").attrib["name"]
else:
# remove()删除子元素,不能删除非子元素
print(node)
root.remove(node)
# 写回文件
tree.write("second.xml", encoding="utf-8")
# 自己创建XML,创建根节点
new_xml = ET.Element("root")
# 创建根节点的子节点
child1 = ET.SubElement(new_xml, "name", attrib={"name": "郭磊"})
age1 = ET.SubElement(child1, "age", attrib={"name": "age"})
sex1 = ET.SubElement(child1, "sex", attrib={"name": "sex"})
age1.text = "18"
sex1.text = "男"
# 创建根节点的子节点
child2 = ET.SubElement(new_xml, "name", attrib={"name": "夏明"})
age2 = ET.SubElement(child2, "age", attrib={"name": "age"})
sex2 = ET.SubElement(child2, "sex", attrib={"name": "sex"})
age2.text = "28"
sex2.text = "女"
# 增加XML格式缩进
def prettify(elem):
"""将节点转换成字符串,并添加缩进。
"""
rough_string = ET.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
print(type(reparsed))
return reparsed.toprettyxml(indent="\t")
root = prettify(new_xml)
print(type(root))
f = open("test.xml", "w", encoding="utf-8")
f.write(root)
f.close()
# 生成文档对象,增加自动换行之后不能使用此方法了
et = ET.ElementTree(new_xml)
et.write("test.xml", encoding="utf-8", xml_declaration=True)
# 另外一种方式创建XML
# 直接解析xml文件
tree = ET.parse("first.xml")
# 一切皆是对象, 对象都是由类创建
# tree 由 ElementTree 类创建
# tree 有2个方法 getroot() 获取xml根节点 和 write() 将内存中的xml写入到文件中
print(type(tree)) # xml.etree.ElementTree.ElementTree
# 获取xml根节点 Element类型
root = tree.getroot()
print(type(root)) # xml.etree.ElementTree.Element
# print(root.tag)
# print(root.attrib)
# print(root.text)
# 创建节点 Element类型
son = root.makeelement("tt", {"k1": "k2"})
sun = son.makeelement("ww", {"k2": "k2"})
# 直接使用Element类也可以创建节点
son1 = ET.Element("mm", {"k3": "k4"})
sun1 = ET.Element("rr", {"k5": "k6"})
print(type(son))
# 加入节点
son.append(sun)
son1.append(sun1)
root.append(son)
root.append(son1)
# short_empty_elements=False 禁止自闭合
# 一般不需要禁止自闭合,默认True即可
# 将内存中的xml写入到文件中
tree.write("first_2.xml", encoding="utf-8", short_empty_elements=False)
# 创建带命名空间的XML
ET.register_namespace("x", "http://www.xjl.com")
root = ET.Element("{http://www.xjl.com}data")
son = ET.SubElement(root, "{http://www.xjl.com}country", attrib={"name": "city"})
tree = ET.ElementTree(root)
tree.write("namespace.xml", encoding="utf-8", xml_declaration=True)