table of Contents
os module
effect
Interact with the operating system, control files / folders
File operation
To determine whether the file
res=os.path.isfile(r'D:\上海python12期视频\python12期视频\day 16\00 上节课回顾.md')
print(res)
Delete Files
os.remove(r'D:\上海python12期视频\python12期视频\day 16\00 上节课回顾.md')
Rename the file
os.rename(r'',r'')
Folder operations
Determine whether the folder
os.path.isdir()
Create a folder
os.mkdir(r'D:\上海python12期视频\python12期视频\test')
Delete the folder
os.rmdir(r'D:\上海python12期视频\python12期视频\test')
List Folder All files
res=os.listdir(r'D:\上海python12期视频\python12期视频\day 16')
print(res)
Helper
Where the files in the current folder
res=os.getcwd()
print(res)
The current path of the file where the specific
#__file__ 是pycharm都有的
print(__file__)
res=os.path.abspath(__file__)#根据不同的操作系统,更换不同的/或\
print(res)
File folders
res=os.path.dirname(os.path.abspath(__file__))
print(res)
Splicing file path
res=os.path.join(os.path.dirname(os.path.abspath(__file__)),'test.py')
print(res)
Road King to determine whether there is (files and folders that are applicable)
res=os.path.exists(r'D:\上海python12期视频\python12期视频\day 16\01 os模块.py')
print(res)
Code execution terminal
res=os.system('dir')
print(res)
sys module
effect
Interact with the python interpreter
The most commonly used when using the command line to run the file and accept the extra parameters
res=sys.argv
print(res)
Modules currently get Imported
print(sys.modules.keys())
To understanding
print(sys.api_version)#解释器的C的API版本
print(sys.copyright)#记录python版权相关的东西
print(sys.version)#获取Python解释程序的版本信息
print(sys.hexversion)#获取Python解释程序的版本值,16进制格式如:0x020403F0
json module and pickle module
effect
json module: cross-platform data exchange, json string
The pickle module: Do not cross-platform, is on the python all data types, such as the collection, use and as json
json
Serialization: a specific collation (JSON strings - the cross-platform interaction ", the transmission data)
Deserialization: specific rules json string into the python / Java / C / PHP required data type
import json
dic=[1,(1,2)]
res=json.dumps(dic)
print(json.dumps(dic))
res=json.loads(res)
import json
def dic():
print('func')
#序列化
with open('test.json','w',encoding='utf-8') as fw:
json.dump(dic,fw)
# 反序列化
with open('test.json','r',encoding='utf-8') as fr:
data=json.load(fr)
print(data)
pickle
def func(): # 针对地址而言,只存了一个函数名
print('func')
with open('test.pkl','wb') as fw:
pickle.dump(func,fw)
with open('test.pkl', 'rb') as fr:
data = pickle.load(fr)
print(type(data), data)
data() # func()
logging module
v1
#日志级别(如果不设置,默认显示30以上)
#v1
logging.info('info') # 10
logging.debug('debug') # 20
logging.warning('wraning') # 30
logging.error('error') # 40
logging.critical('critical') # 50
v2
# v2 --> 添加设置
logging.basicConfig(filename='20190927.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
username = 'nick'
goods = 'bianxingjingang'
logging.info(f'{username}购物{goods}成功') # 10
v3
# 1. 配置logger对象
nick_logger = logging.Logger('nick')
json_logger = logging.Logger('jason')
# 2. 配置格式
formmater1 = logging.Formatter('%(asctime)s - %(name)s -%(thread)d - %(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. 配置handler --> 往文件打印or往终端打印
h1 = logging.FileHandler('nick.log')
h2 = logging.FileHandler('json.log')
sm = logging.StreamHandler()
# 4. 给handler配置格式
h1.setFormatter(formmater1)
h2.setFormatter(formmater2)
sm.setFormatter(formmater3)
# 5. 把handler绑定给logger对象
nick_logger.addHandler(h1)
nick_logger.addHandler(sm)
json_logger.addHandler(h2)
# 6. 直接使用
nick_logger.info(f'nick 购买 变形金刚 4个')
# json_logger.info(f'json 购买 变形金刚 10个')
cv Dafa
import os
import logging.config
# 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' # 其中name为getLogger()指定的名字;lineno为调用日志输出函数的语句所在的代码行
simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
# 定义日志输出格式 结束
logfile_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # log文件的目录,需要自定义文件路径 # atm
logfile_dir = os.path.join(logfile_dir, 'log') # C:\Users\oldboy\Desktop\atm\log
logfile_name = 'log.log' # log文件名,需要自定义路径名
# 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir): # C:\Users\oldboy\Desktop\atm\log
os.mkdir(logfile_dir)
# log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name) # C:\Users\oldboy\Desktop\atm\log\log.log
# 定义日志路径 结束
# log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
},
'filters': {}, # filter可以不定义
'handlers': {
# 打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
# 打印到文件的日志,收集info及以上的日志
'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': logfile_path, # 日志文件
'maxBytes': 1024 * 1024 * 5, # 日志大小 5M (*****)
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
},
'loggers': {
# logging.getLogger(__name__)拿到的logger配置。如果''设置为固定值logger1,则下次导入必须设置成logging.getLogger('logger1')
'': {
# 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'handlers': ['default', 'console'],
'level': 'DEBUG',
'propagate': False, # 向上(更高level的logger)传递
},
},
}
def load_my_logging_cfg():
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(__name__) # 生成一个log实例
logger.info('It works!') # 记录该文件的运行状态
return logger
if __name__ == '__main__':
load_my_logging_cfg()
import time
import logging
import my_logging # 导入自定义的logging配置
logger = logging.getLogger(__name__) # 生成logger实例
def demo():
logger.debug("start range... time:{}".format(time.time()))
logger.info("中文测试开始。。。")
for i in range(10):
logger.debug("i:{}".format(i))
time.sleep(0.2)
else:
logger.debug("over range... time:{}".format(time.time()))
logger.info("中文测试结束。。。")
if __name__ == "__main__":
my_logging.load_my_logging_cfg() # 在你程序文件的入口加载自定义logging配置
demo()
from settings import load_my_logging_cfg
user_logger = load_my_logging_cfg()
user_logger.info('用户死了')