package
Before we talked about the module, but if a module's function too, it would seem more trouble. If it directly into multiple files, will not only change the way imported, and users will have caused no small trouble, after all, different functions in different files, it still fails to find a user a? This time the package appeared usage
What is the package? After the package is a module divided into multiple files, and import the same manner, with the packages or from m1 import f1, the user feels no change
Package is a folder, but which must have __init__ this file in nature. In other words, __ init__ make an ordinary folder into a bag, guide package is the guide inti
The first way to use
from m1 import f1
from m1 import * # 运行init这个文件,创建一个init这个名称空间,然后把inti内的变量丢入 init 这个名称空间内
f1() # 导包以执行文件的环境变量为基准
f2()
f3()
f4()
# import sys
# print(sys.path)
import requests
from m1 import f1()
from m1 import f7
f7()
Although this method is feasible but not recommended
Package guide is introduced init
Package of environmental variables executable file as a reference, init package can only start importing from the package name
Relative import: (only in the package)
Is the current directory
.. the parent directory
time module
Timestamp
print(time.time()) # 1565958257.9459026
This is the time in 1970 to the present
But this time the child will see a lot of trouble
Formatting time
# year month day X
print(time.strftime('%Y_%m_%d %X')) # 2019_08_16 10:26:36
This more comfortable
Structured time
print(time.localtime()) # 当地时间(中国)
print(time.gmtime()) # 标准时间
Three kinds of time format conversion
# 结构化时间转格式化时间
print(time.strftime('%Y-%m-%d %X', time.localtime()))
# 格式化时间转结构化时间
print(time.strptime('2019-08-16 10:30:44', '%Y-%m-%d %X'))
# 结构化时间转时间戳
print(time.mktime(time.localtime()))
# 时间戳转结构化时间
print(time.localtime(time.time()))
Emphasis
time.time()
time.sleep(2)
datetime module
import datetime
print(datetime.datetime.now()) # 打印时间
now = datetime.datetime.now()
print(now+datetime.timedelta(3)) # 默认+3天
print(now+datetime.timedelta(hours=3)) # 3小时
print(now+datetime.timedelta(minutes=3)) # 3分钟
print(now.replace(year=1900))
os module
mport os
print(os.getcwd()) # 获取当前文件目录
os.mkdir('m2') # 创建一个文件夹
os.rmdir('m2') # 删除文件夹
res = os.listdir(r'D:\上海Python11期视频\python11期视频\day 17') # 列出所有文件
print(res)
os.rename('test.py','test1.py')
os.remove('test1.py')
__file__ only pycharm was provided, python itself does not support
print('os.path.abspath(__file__):',os.path.abspath(__file__)) # 支持不同的平台(windows,ios,andirod,linux,unix)
rint(os.path.exists('01 包.py')) # 文件不存在False,存在True
print(os.path.exists('01 包.py')) # 文件不存在False,存在True
print(os.path.isfile('01 包.py')) # 是否为文件
print(os.path.isdir('01 包.py')) # 是否为文件夹
# ********(经常使用)
# 支持不同的平台(windows,ios,andirod,linux,unix)
res = os.path.join(r'D:\上海Python11期视频\python11期视频\day 17\m1\bbb','m5.py') # 拼接文件路径
res = os.path.join(r'D:\上海Python11期视频\python11期视频\day 17\m1\bbb','m5','test.py') # 拼接文件路径
# print(r'D:\上海Python11期视频\python11期视频\day 17\m1\bb'+'\m5.py')
print(res)
# ******* (经常使用)
print(os.path.abspath(__file__))
print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import os
g = os.walk(r'D:\上海Python11期视频\python11期视频\day 17') # 返回三个值,第一个值是路径;第二个值是路径下的文件夹,第三个值是路径下的文件
for i in g:
print(i)
sys module
#sys模块: 与Python解释器交互
import sys
# print(sys.path) # 路径
print(sys.argv) # 接收参数(用cmd执行文件时运行才有效)
print(sys.modules)
json
# json模块:
# 用python写了一个程序,用java写了一门程序,这两个程序需要数据之间交流,规定了一种多种语言通用的数据类型,json串
# 序列化:从python的字典(最常用)变成json串, dump
# 反序列化:从json串变成python的字典(最常用),load
import json
dic = {'a': 1, 'b': 'abc', 'c': None}
data = json.dumps(dic) # 序列化到内存中
print(data,type(data)) # 单引号全部变成双引号
data = json.loads(data) # 从内存中获取json串
print(data,type(data))
with open('test.json','w',encoding='utf8') as fw:
json.dump(dic,fw)
with open(f'{"test"}.json','r',encoding='utf8') as fr:
data = json.load(fr)
print(data)
pickle module
But when the method is similar to json be deserialized when the pickle executable file export function, can only export the file to perform the function of the same name, because the pickle store only function is to store the address, and not stored value of the function
# 文件1
def func():
x = 3
print(x)
import pickle
with open('test.pkl','wb') as fw:
pickle.dump(func,fw)
# 文件2
with open('test.pkl', 'rb') as fr:
data = pickle.load(fr)
data()
print(data)
As the above code, if an error is reported to run the file 2, file 2 because there are no defined function FUNC (), also defined even only shows the functions defined in the file
In other words, pickle deserialization function is useless
hashlib module
Generally used for secret password
import hashlib
m = hashlib.md5() # 固定的写法
m.update(b'123456')
# m.update(b'456')
print(m.hexdigest())
After the hash features:
- It becomes a fixed character string
- The same result as the hash string
- Superposition
hmac module
import hmac
m = hmac.new(b'abc') # 加盐
m.update(b'123456')
# m.update(b'456')
print(m.hexdigest())
Hashlib similar method, but the administrator can set a key value, the more difficult to decipher
logging module
General logging modules are applied template, not explained in detail here
```
mport logging
logging.debug ( 'debugging') # 10
logging.info ( 'normal') with which a # 20 #
logging.critical ( 'serious error') # 30
logging.error ( 'error') # 40
logging.warning('警告') # 50
The default can output more than 30
v2 log information recorded in the file which
logging.basicConfig(filename='access.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
logging.debug ( 'debugging') # 10
logging.info ( "normal information") # 20
logging.warning ( 'warning') # 30
logging.error ( 'error message') # 40
logging.critical ( 'serious error') # 50
1. Create a logger objects
logger = logging.getLogger('hyc')
2. Generate format
formmater1 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',)
formmater2 = logging.Formatter('%(asctime)s : %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',)
formmater3 = logging.Formatter('%(name)s %(message)s',)
3. Create a file object
h1 = logging.FileHandler('h1.log')
h2 = logging.FileHandler('h2.log')
sm = logging.StreamHandler()
4. Bind file format
h1.setFormatter (formmater1)
h2.setFormatter (formmater2)
sm.setFormatter (formmater3)
5. Binding documents
logger.addHandler(h1)
logger.addHandler(h2)
logger.addHandler(sm)
6. Control Level
logger.level = 50
7. Use
logger.debug ( 'debugging') # 10
logger.info ( 'normal information') # 20 is
logger.warning ( 'warning') # 30
logger.error ( 'error message') # 40
logger.critical ( 'serious error message ') # 50