Module day16 classroom summary

json module

  1. Sequence of: the type of data stored into the python json string
  2. Deserialization: json string read into the data type python

Cross-platform

dict/list

dic = {'a':1}

# 内存中转化
data = json.dumps(dic)
data = json.loads(data)

# 文件中转化
with open() as fw:
    json.dump(dic, fw)
with open() as fr:
    data = json.load(fr)

pickle module

We can not be cross-platform, but supports all data types python

dic = {'a':1}

# 内存中转化
data = pickle.dumps(dic)
data = pickle.loads(data)

# 文件中转化
with open() as fw:
    pickle.dump(dic, fw)
with open() as fr:
    pickle = json.load(fr)

os module

And to interact with the operating system

os.path.join()  # 拼接地址
os.path.listdir()  # 列出文件夹内的所有文件
os.path.dirname()  # 获取上 一级目录
os.path.abspath()  # 获取文件的绝对路径
os.path.exists()  # 文件是否存在

sys module

And to interact with python interpreter

sys.argv # 用cmd执行python文件的时候获取参数


sys.path # 获取环境变量

logging module

import logging

# 1. 生成logger对象
logger = logging.getLogger('nick')
logger1 = logging.getLogger('jason')

# 2. 格式
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. 打印对象
h1 = logging.FileHandler('h1.log')
sm = logging.StreamHandler()

# 4. 打印对象绑定格式
h1.setFormatter(formmater1)
sm.setFormatter(formmater2)

# 5. logger绑定打印对象
logger.addHandler(h1)
logger.addHandler(sm)

# 6. 设置级别
logger.setLevel(50)

logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')

Guess you like

Origin www.cnblogs.com/shin09/p/11600354.html