首页 > 技术文章 > python 常用模块

huay 2019-10-06 10:14 原文

常用模块


importlib

模块导入

1.创建包xx
2.创建模块oo.py

NAME = "小黑"


class Person(object):
    def __init__(self, name):
        self.name = name

    def dream(self):
        print("{}在做美梦!".format(self.name))
View Code

 


3.引入模块

# from xx import oo

# print(oo.NAME)
# p = oo.Person("赵导")
# p.dream()



s = "xx.oo"

# m, n = s.split(".")
# from m import n
#
# p = n.Person("赵导")
# p.dream()

import importlib

# 根据字符串导入模块
# 通畅用来导入包下面的模块
o = importlib.import_module("xx.oo")
s2 = "Person"

# 由字符串找函数、方法、类  利用 反射
the_class = getattr(o, "Person")
p2 = the_class("小黑")
p2.dream()


# print(o.NAME)
# p = o.Person("赵导")
# p.dream()
View Code

 

json

json.dumps()

转成json

import json

dict={'k1':'v1','k2':'中文'}
ret=json.dumps(dict,ensure_ascii=False)#ensure_ascii=False避免中文转成unicode
print(ret)
'''
输出结果
{"k1": "v1", "k2": "中文"}
'''
View Code

json.loads()

json转成其他

import json

res='{"k1": "v1", "k2": "中文"}'
r=json.loads(res)
print(r,type(r))
'''
输出结果
{'k1': 'v1', 'k2': '中文'} <class 'dict'>
'''
View Code

json.dump()

存入

import json
'''
以json格式存入文本
'''
dict={'k1':'v1','k2':'中文'}
with open('test.json', 'w',encoding='utf-8') as f:
    json.dump(dict, f,ensure_ascii=False)
View Code

json.load()

读取

import json
'''
读取json
'''
f=open('test.json','r',encoding='utf-8')
ret=json.load(f)
print(ret)
View Code

 

加密算法

后续补充。。。

sys

 

os

 

time

import time
#获取时间戳
t=time.localtime()
print(t)
#时间戳转格式化时间
date_str=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(date_str)

#格式化时间装时间戳
str_time = '2019-02-26 13:04:41'
t2=time.mktime(time.strptime(str_time, '%Y-%m-%d %H:%M:%S'))
print(t2)

  

案例

import time

# ret=time.strftime("%Y-%m-%d %X")
# print(ret)
# '''
# 2019-11-03 18:23:04
# '''
#获取当前格式化时间
# r2=time.strftime("%Y-%m-%d %H-%M-%S")
# print(r2)
# '''
# 2019-11-03 20-24-54
# '''


#从格式化转成时间戳
str='2019-11-03 20:24:54'
#用格式匹配上面格式时间
rs=time.strptime(str,"%Y-%m-%d %H:%M:%S")
rs2=time.mktime(rs)
print(rs2)

#从时间戳转成固定格式

tis=1572783894
ts1=time.localtime(tis)
print(ts1)
#指定转换格式
ts2=time.strftime("%Y-%m-%d %H:%M:%S",ts1)
print(ts2)
ts3=time.strftime("2011"+"-%m-%d %H:%M:%S",ts1)
print(ts3)
View Code

 

datetime

 获取7天后时间

"""
时间间隔
"""

import datetime
now = datetime.datetime.now()  # 你领了一张有效期为7天的优惠券
print(now)
# 时间间隔
d7 = datetime.timedelta(weeks=1)
# 求失效时间
ret = now + d7
print(ret)
View Code

 

urllib

http相关

1.urlencode

from urllib.parse import urlencode

v={'k1':'v1','k2':'v2'}
res=urlencode(v)
print(res)
'''
结果
k1=v1&k2=v2
'''
View Code

random

生成随机数0-25随机数

"""
求一个0~255的随机数
"""


import random
ret = random.randint(0, 255)
print(ret)


# 如何生成五位数的字母和数字随机组合的验证码, "A3bv7"
tmp_list = []
for i in range(5):
    u = chr(random.randint(65, 90))  # 生成大写字母
    l = chr(random.randint(97, 122))  # 生成小写字母
    n = str(random.randint(0, 9))  # 生成数字,注意要转换成字符串类型

    tmp = random.choice([u, l, n])
    tmp_list.append(tmp)

print("".join(tmp_list))
View Code

 

 

 

 

 

 

 

 

推荐阅读