python学习随笔

1、读取/写入json文件

import json

def format_json(json_file, dics):
    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(dics, f, indent=4, ensure_ascii=False)

def load_json(json_file):
    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"{json_file} is not found.")
        return None

if __name__ == '__main__':
    dics = {'name': 'zhangsan'}
    json_file = 'test.json'
    format_json(json_file, dics)
    dic1 = load_json(json_file)
    if dic1 is not None:
        print(dic1)

2、多线程

def worker(delay=1):
    time.sleep(delay)
    print(f'sleep1=====>>>{delay}')

if __name__ == '__main__': # thread thread1 = threading.Thread(target=worker, args=(1,)) thread2 = threading.Thread(target=worker, args=(2,)) thread1.start() thread2.start() thread1.join() thread2.join()

 

3、lambda表达式(最基础的用法)

x = lambda a, b, c : a * b + c
print(x(2, 4, 5))

##########
13

4、列表推导式和生成器表达式

# 获取当前目录下的所有bin文件,且以'_'开头
import os
bin_files = [bin for bin in os.listdir('.') if bin.endswith('.bin') if bin.startswith('_')]
print(bin_files)

  生成器表达式得到的是元组

5、读取或写入bin/npy文件

def create_npy(shape1=(1,3,12,12), dtype='float32', _min=-5, _max=5):
    # 生成数据
    data = np.random.rand(*shape1) * (_max - _min) + _min
    data = data.astype(dtype)
    # 保存数据
    np.save("xxx1.npy", data)
    # 读取npy数据
    npy_data = np.load("xxx1.npy")
    print(npy_data.shape)
    print(npy_data.dtype)
    # 保存bin数据
    npy_data.astype(dtype).tofile("xxx1.bin")
    # 读取bin文件
    bin_data = np.fromfile("xxx1.bin", dtype=dtype)
    print(bin_data)

6、pytest魔法文件

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption("--quant", action="True", help="run with quant.")

def str_to_bool(s):
    if s.lower() == 'flase':
        return False
    elif s.lower() = 'true':
        return True

@pytest.fixture
def quant_flag(request):
    return str_to_bool(request.config.getoption("--quant"))

  

 

posted @ 2026-05-28 19:57  一只野生的小胖鱼  阅读(8)  评论(0)    收藏  举报