day 16 Summary

1.os module

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'文件名')

Rename the file

os.rename(r'原文件名','修改文件名')

Folder operations

Determine whether the folder

os.path.isdir()

Create a folder

is not os.path.exists(r'D:\上海python12期视频\python12期视频\test')
    os.mkdir(r'D:\上海python12期视频\python12期视频\test')

Delete the folder

os.rmdir(r'D:\上海python12期视频\python12期视频\test')

Lists all files within a folder (****)

res = os.listdir(r'D:\上海python12期视频\python12期视频\test')
print(res)

Supplementary

Where the files in the current folder

res = os.getcwd()
print(res)

Current file specific path

file    pycharm独有
print('__file__:',__file__)
res = os.path.abspath(__file__)  # 根据不同的操作系统,更换不同的\或/
print(res)

File folders

res = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(res)

Splicing file path

res = os.path.join.(os.path.dirname(os.path.abspath(__file__))),'img','test.jpg')
print(res)

Determine whether there is a path (file or folder apply)

res = os.path.exists(r'D:\上海python12期视频\python12期视频\test')
print(res)

Try not to write path

To understanding

Code execution terminal

rse = os.system('dir')
print(res)

2.sys module

Interact with the python interpreter

The most commonly used when running a file using the command line, to accept the extra parameters

import sys


res = sys.argv
print(res)

Modules currently get Imported

print(sys.modules.keys())

To understanding

sys.argv Command line parameters List, the first element is the path to the program itself
sys.modules.keys() Returns a list of all the imported modules
sys.exc_info() For more information on obtaining an exception currently being handled exception class, exc_type, exc_value, exc_traceback currently being processed
sys.exit(n) Exit the program, when the normal exit exit (0)
sys.hexversion Gets the version of Python interpreter value, hexadecimal formats such as: 0x020403F0
sys.version Version Get Python interpreter
sys.maxint The maximum value of Int
sys.maxunicode The maximum value of the Unicode
sys.modules Return system imported module field, key is the module name, value module is
sys.path Back module search path, using initialization value of the environment variable PYTHONPATH
sys.platform Returns the name of the operating system platform
sys.stdout Standard output
sys.stdin Standard Input
sys.stderr Error output
sys.exc_clear() To clear the current thread that appears in the current or most recent error message
sys.exec_prefix Returns the platform-independent file installation location python
sys.byteorder Local rule pointer byte, the value of the platform is big-endian 'big', the value of little-endian platform is 'little'
sys.copyright Record python copyright-related stuff
sys.api_version API versions of C interpreter

3.json and pickle module

json module: cross-platform data exchange, json string

The pickle module: Do not cross-platform python for all data types, such as collection, use exactly the same way and json

Serialization: arrangement in accordance with specific rules (JSON string - a cross-platform interaction>, transmission of data)

Deserialize: converting json string into python / java / c / php specific rules required data type

Learn what serialization and de-serialization is

import json

dic = [1,(1,2)]

res = json.jumps(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.jump(dic,fw)

Deserialization

with open('test.json','r',encoding='utf8') as fr:
    data = json.load(fr)
    print(type(data),data)
    
    
goods = {
    1:'awaw',
}

with open('nick,json', 'r', encodingn='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)

pickle

import pickle  # 未来存对象

def func():  # 针对地址而言,只存了一个函数名
    print('func')
    
with open('test.pkl','wb') as fw:
    pickle.dump(func,fw)
    
    
def func():
    print('asdglaads')
    
with open('test.pkl', 'rb') as fr:
    data = pickle.load(fr)
    print(type(data),data)
    data()  # func()

4.logging module

import logging

# 日志级别(如果哦不设置,默认显示30以上)
# v1
logging.info('info')  # 10
logging.debug('debug') # 20
logging.warning('wraning')  # 30
logging.error('error')  # 40
logging.critical('critical')  # 50

# 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')

# 配置格式
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大法

Guess you like

Origin www.cnblogs.com/LZF-190903/p/11600615.html