os module / sys module / json / pickle module / logging module (day16 finishing)

Content Today

os module

File operation

  1. To determine whether the file isfile

    import os
    res = os.path.isfile(r'D:\上海python12期视频\python12期视频\day 16\00 上节课回顾.md')
    print(res)
  2. Remove deleted files

    os.remove(r'')
  3. Rename the file rename

    os.rename(r'', r'')

This folder

  1. Determine whether the folder isdir

    os.path.isdir()
  2. Create a folder mkdir

    os.mkdir(r'D:\上海python12期视频\python12期视频\test')
  3. Delete a folder rmdir

    os.rmdir(r'D:\上海python12期视频\python12期视频\test')
  4. Lists all files within a folder listdir

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

Supplementary

  1. Where the files in the current folder getcwd

    res = os.getcwd()print(res)
  2. Specific path of the current file __file__ and abspath

    print('__file__:', __file__)
    res = os.path.abspath(__file__)  # 根据不同的操作系统,更换不同的\或/
    print(res)
  3. The folder where the file dirname

    res = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    print(res)
  4. Splicing file path join

    res = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'img', 'test.jpg')
    print(res)
  5. Determine whether there is a path (file or folder apply) exists

    res = os.path.exists(r'D:\上海python12期视频\python12期视频\day 16\01 os模块.py')
    print(res)

To understanding

  1. Destination code execution system

    res = os.system('dir')
    print(res)
  2. Code statistics

    import os
    import sys
    
    
    ## 代码统计(只是想告诉你os模块的应用场景)
    def count_code(file_path):
        """通过文件路径计算文件代码量"""
        count = 0
        # tag = False
        # tag2 = False
        with open(file_path, 'r', encoding='utf8') as fr:
            for i in fr:
                # if ('= """' or "= '''") in i:
                #     tag2 = True
                # if tag and (i.startswith('"""') or i.startswith("'''")) and not tag2:
                #     tag = False
                # if tag and not (i.startswith('"""') or i.startswith("'''")) and not tag2:
                #     continue
                if i.startswith('#'):
                    continue
                if i.startswith('\n'):
                    continue
                # if i.startswith('"""') or i.startswith("'''"):
                #     tag = True
                #     continue
                count += 1
        # 计算代码量
        return count
    
    
    def count_all_file_code(top):
        if os.path.isfile(top):
            count = count_code(top)
            return count
    
        # 针对文件夹做处理
        res = os.walk(top)  # 只针对文件夹
        count_sum = 0
        for dir, _, files in res:
            # print(i) # 所有文件夹名
            # print(l) # i文件夹下对应的所有文件名
            for file in files:
                file_path = os.path.join(dir, file)
                if file_path.endswith('py'):  # 判断是否为py文件
                    count = count_code(file_path)
                    count_sum += count
        return count_sum
    
    
    try:
        _, top = sys.argv
    except:
        top = r'D:\上海python12期视频\python12期视频\项目-atm'
    
    count_sum = count_all_file_code(top)
    print(f' {top} 代码量统计: {count_sum}')
    

sys module

And interactive python interpreter

  1. When you use the command line to run the file and accept the extra parameters argv

    res,res1... = sys.argv  # 可以为多个
  2. All methods modules.keys modules currently introduced in

    print(sys.modules.keys())
  3. To understanding

    print(sys.api_version)
    
    print(sys.copyright)
    
    print(sys.version)
    
    print(sys.hexversion)

pickle and json modules

json module

Cross-platform data exchange, json string, can store numbers, strings, lists, dictionaries, Boolean value, None. Not deposit collections, etc.

  • Serialization: arranged according to a specific rule (JSON string, interactive data transfer across the internet)

    dump和dumps

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

    load and loads

import json

dic = [1, (1, 2)]

# 1. dumps和loads是针对运行时内存中的传输转换  
res = json.dumps(dic)  # json串中没有单引号,
print(type(res), res)  # 跨平台数据交互

res = json.loads(res)
print(type(res), res)

# 2. dump和load时针对存储在文件中时的传输转换
# 序列化
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)    

pickle module

Do not cross-platform, python for all data types, such as the collection, use and json exactly the same (used to keep the object name)

def func():  # 针对地址而言,只存了一个函数名
    print('func')

with open('test.pkl','wb') as fw:
    pickle.dump(func,fw)

logging module

Log Level

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

Add Setting

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

Custom Configuration

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

Guess you like

Origin www.cnblogs.com/wick2019/p/11600778.html