1.os module
Interact with the operating system, it provides the interface to access the underlying operating system, used to control the file / folder
import os
1. File Operations
1) to determine whether to file:
res=os.path.isfile(r'K:\Python课程\上课视频\day14\04 模块的搜索路径.py')
print(res) #True
2) delete the file:
os.remove(r'K:\Python课程\上课视频\day14\.idea\11.py')
3) Rename the file:
os.rename(r'test.py',r'test1.py')
2. Folder actions:
Whether 1) determine the folder:
res=os.path.isdir(r'K:\Python课程\上课视频\day14\.idea')
print(res) #True
2) Create a folder:
if not os.path.exists(r'K:\Python课程\上课视频\day14\11.py'):
os.mkdir(r'K:\Python课程\上课视频\day14\11.py')
3) Delete the folder:
os.rmdir(r'K:\Python课程\上课视频\day14\11.py')
4) a list of all files within the folder:
res=os.listdir(r'K:\Python课程\上课视频\day14\.idea')
print(res)
运行结果:
['day14.iml', 'inspectionProfiles', 'misc.xml', 'modules.xml', 'workspace.xml']
Supplementary
1) the current file folder where :( that is the current directory path Python script to work)
res=os.getcwd()
print(res)
2) the specific path of the current file
print('__file__:',__file__)
res=os.path.abspath(__file__) #根据不同的操作系统,更换不同的\或/
print(res)
File 3) File folders
res=(os.path.dirname(os.path.abspath(__file__)))
print(res)
4) splicing file path:
res=os.path.join(os.path.dirname(os.path.abspath(__file__)),'img','test.jpg')
print(res)
5) determining whether there is a path (file or folder apply)
res=os.path.exists(r'K:\Python课程\上课视频\day14\img\test.jpg')
print(res) #False
6) executing terminal Code:
res = os.system('dir')
print(res)
2.sys module
Python interpreter to interact with, offers a range of functions and variables to manipulate Python runtime environment
import sys
The most common is when a file operation command line, the extra parameters received
res=sys.argv
print(res)
Modules currently get Imported
import requests
print(sys.modules.keys())
request=__import__('requests')
print(sys.api_version)
print(sys.copyright)
print(sys.version)
print(sys.hexversion)
3.json and pickle modules:
1) json module: cross-platform data exchange, json string
2) pickle module: Do not cross-platform, Python for all data types, such as the collection, use and as json
3) the sequence of: regularly arranged in a specific (JSON strings - the cross-platform interaction ", the transmission data
4) deserialization: converting json string into Python / java / c / php specific rules required data type
import json
dic=[1,(1,2)]
res=json.dumps(dic) #json串没有单引号
print(type(res),res) #跨平台数据交互
res=json.loads(res)
print(type(res),res)
dic={'a':True,'b':None}
#序列化字典为json串,并保存文件
import json
def dic():
print('func')
with open('test.json','w',encoding='utf8') as fw:
json.dump(dic,fw)
#反序列化
with open('test.json','r',encoding='utf8')as fr:
data=json.load(fr)
print(type(data),data)
goods={
1:'wawa',
}
with open('nick.json','r',encoding='utf8') as fr:
data=json.load(fr)
data['wawa']=1
data['extra']-=10
data['locked']=1
with open('nick.json','w',encoding='utf8') as fw:
json.dump(data,fw)
import pickle #未来存对象(存对象名)
def func(): #针对地址而言,只存了一个函数名
print('func')
with open('test.pkl','wb') as fw:
pickl.dump(func,fw)
def func():
print('kkas')
with open('test.pkl','rb') as fr:
data=pickle,load(fr)
print(type(data),data)
data() #func()
4.logging module
Log total is divided into five levels, the five-level bottom-up match debug -> info -> warning -> error -> critical
#v1
import logging
logging.debug('调试信息') #10
logging.info('正常信息') #20
logging.warning('警告信息') #30
logging.error('报错信息') #40
logging.critical('严重错误信息') #50
运行结果:
WARNING:root:警告信息
ERROR:root:报错信息
CRITICAL:root:严重错误信息
v1 version does not specify the level of the log; unable to specify the format of the log; only to screen print, can not not write the file, and if you do not set the log level, the default display 30 or more.
#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个')