os模块、sys模块、json和pickle模块、logging模块

os模块:与操作系统交互,控制文件/文件夹

一、对文件操作

1.判断是否为文件

res = os.path.isfile(r'D:上海python12期视频python12期视频day 160 上节课回顾.md') print(res)
2. 删除文件  
os.remove(r'')
3. 重名名文件
os.rename(r'旧名字', r'新名字')

二、对文件夹操作

1.判断是否为文件夹
os.path.isdir()
2.创建文件夹
if not os.path.exists(r'D:上海python12期视频python12期视频 est'):
    os.mkdir(r'D:上海python12期视频python12期视频 est')
3.删除文件夹
os.rmdir(r'D:上海python12期视频python12期视频 est')
4.列出文件夹内所有的文件
res = os.listdir(r'D:上海python12期视频python12期视频day 16')
print(res)

三、辅助性的

1.当前文件的所在文件夹 res = os.getcwd() print(res)
2.当前文件所在的具体路径 

 __file__ pycharm独有

print('__file__:', __file__)

res = os.path.abspath(__file__)  # 根据不同的操作系统,更换不同的或/

print(res)
3.文件的文件夹
res = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

print(res)
4.拼接文件路径

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

print(res)
5.判断路径是否存在(文件or文件夹都适用)

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

print(res)

四、了解

1.res = os.system('dir')

print(res)

2.res = os.walk(r'D:上海python12期视频python12期视频day )  #遍历

res = os.walk(top)  
for dir, _, files in res: for file in files: file_path = os.path.join(dir, file)
top = r' '

案例:统计代码量

## 代码统计(只是想告诉你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('
'):
                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


top = r'D:上海python12期视频python12期视频项目-atm'
count_sum = count_all_file_code(top)
print(f' {top} 代码量统计: {count_sum}')

 sys模块:与python解释器交互

最常用的:

res = sys.argv   # 最常用,当使用命令行式运行文件,接收多余的参数   python  文件名.py  123456
print(res)

拿到当前导入的模块 print(sys.modules.keys())
# requests = __import__('requests')

了解:

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

json和pickle模块

json模块: 跨平台数据交互,json串
pickle模块: 不跨平台,针对python所有数据类型,如集合,使用方式和json一模一样
 
序列化: 按照特定的规则排列(json串-->跨平台交互,传输数据)
反序列化: 按照特定的规则把json串转换成python/java/c/php需要的数据类型
import json

dic = [1, (1, 2)]

res = json.dumps(dic)  # json串中没有单引号,
print(type(res), res)  # 跨平台数据交互

res = json.loads(res)
print(type(res), res)
打印结果为:
<class 'str'> [1, [1, 2]]
<class 'list'> [1, [1, 2]]
#序列化字典为json串,并保存文件
import json
dic = [1,(1,2)]
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

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模块

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

# 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个')
原文地址:https://www.cnblogs.com/fjn839199790/p/11599675.html