文件存储与数据处理
概述
板载 7MB FAT 卷挂成 lxfs,没有 open();小参数可以放 EEPROM。本篇覆盖文件读写的全部 API、边界与错误,以及 JSON、校验算法、正则的实际能力。
文件存储
lxfs:没有 open() 的文件系统
板载 FAT 卷由固件挂载,Python 侧通过 lxfs 模块访问。open() 在这个固件里不存在:
>>> open('/main.py')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name not defined
lxfs 的完整 API:
| 函数 | 说明 |
|---|---|
info() | 返回 (总 KB, 可用 KB) |
listdir(path) | 返回名字列表,子目录带 / 后缀 |
read(path) | 读全文,返回 bytes |
write(path, data) | 覆盖写,返回写入字节数 |
append(path, data) | 追加写 |
stat(path) | 返回文件大小 |
remove(path) | 删除 |
sync() | 刷盘 |
mount() / umount() / mkfs() | 手动挂载/卸载/格式化(一般不用碰) |
一次完整的读写示范:
import lxfs
print(lxfs.info()) # (7168, 7099) —— 7MB 卷,可用 7099KB
print(lxfs.listdir('/')) # ['main.py', 'main.bak', 'System Volume Information/', 'verify.txt']
lxfs.write('/cfg.txt', b'line1\n') # 6
lxfs.append('/cfg.txt', b'line2\n') # 6
print(lxfs.read('/cfg.txt')) # b'line1\nline2\n'
print(lxfs.stat('/cfg.txt')) # 12
lxfs.sync() # True
lxfs.remove('/cfg.txt')
print(lxfs.listdir('/')) # []
边界与错误
| 场景 | 结果 |
|---|---|
| 读不存在的文件 | OSError(5,)(EIO) |
stat() 不存在的文件 | OSError(5,) |
写子目录(/sub/x.txt) | OSError(5,)——不支持子目录写入 |
| 中文文件名 | 正常(/中文.txt) |
| 单文件 8KB | 正常写入 |
写文件记得
sync()write() / append() 会进 FAT 缓存,掉电可能丢。关键配置写完立刻 lxfs.sync()。另外根目录不要塞太多文件,FAT 卷的性能和可靠性都随文件数下降。
EEPROM:小参数放这里
8KB 的 24Cxx 适合存「不该被脚本误删」的参数(设备编号、校准值):
import eeprom
print(eeprom.info()) # 容量/地址信息
EEPROM 的读写接口与 lxfs 类似(read / write),区别是它按字节地址操作、容量只有 8KB,而且不受 mkfs() 影响。用它存设备唯一标识比存 FAT 里稳。
数据处理:JSON / 校验 / 正则
JSON
import json
d = json.loads('{"a": 1, "b": "中文", "c": true, "d": null}')
print(json.dumps(d))
实测能力:
| 能力 | 结果 |
|---|---|
| 嵌套对象 / 数组 | 正常 |
| 中文(UTF-8) | 正常,不转义 |
true / false / null | 正常 |
| 浮点 / 大整数 / 负数 | 正常 |
转义字符(\t \n \") | 正常 |
| 非法输入 | 抛 ValueError |
| 空数组 / 空对象 | [] / {} |
| 往返一致性 | 20 层嵌套实测无截断 |
separators= / sort_keys= | 不支持,TypeError |
拼接上报报文的标准写法:
import json
import utime
payload = json.dumps({
'dev': 'YF3028-001',
'ts': utime.time(),
'data': {'t': 25.5, 'h': 61.2},
})
print(payload)
# {"dev": "YF3028-001", "ts": 0, "data": {"t": 25.5, "h": 61.2}}
校验:CRC32 / SHA256 / Base64
import binascii
import hashlib
print(binascii.hexlify(b'\x01\x03')) # b'0103'
print(hex(binascii.crc32(b'123456789'))) # 0xcbf43926
print(hashlib.sha256(b'abc').hexdigest()[:16]) # ba7816bf8f01cfea
crc32 的标准值 0xcbf43926 与 PC 端一致,可以直接和云端对账。
正则
import re
m = re.match(r'(\d+)-(\d+)', '12-34')
print(m.group(), m.group(1), m.group(2)) # 12-34 12 34
print(re.sub(r'\s+', '-', 'a b c')) # a-b-c
print(re.split(r',', 'a,b,c')) # ['a', 'b', 'c']
支持 match / search / sub / split / compile;不支持 groups() 和 findall(),多结果匹配用循环 search + span() 自己切。