Files
pig-house-controller/utils/fs.py
2025-09-07 14:59:46 +08:00

58 lines
1.3 KiB
Python

# 兼容PC和MicroPython的文件操作
# compat_fs.py
try:
import uos as os # MicroPython
MICROPYTHON = True
except ImportError:
import os # CPython
MICROPYTHON = False
def list_dir(path="."):
"""列出目录内容"""
return os.listdir(path)
def make_dir(path):
"""创建目录"""
if MICROPYTHON:
os.mkdir(path)
else:
os.makedirs(path, exist_ok=True)
def remove_file(path):
"""删除文件"""
os.remove(path)
def read_file(path, mode="r"):
"""读取文件内容"""
with open(path, mode) as f:
return f.read()
def write_file(path, data, mode="w"):
"""写入文件内容"""
with open(path, mode) as f:
f.write(data)
def is_file(path):
"""判断是否是文件"""
try:
st = os.stat(path)
# MicroPython: stat()[0] >> 14 & 0xF == 8 表示普通文件
if MICROPYTHON:
return (st[0] >> 14) & 0xF == 8
else:
return os.path.isfile(path)
except OSError:
return False
def is_dir(path):
"""判断是否是目录"""
try:
st = os.stat(path)
if MICROPYTHON:
return (st[0] >> 14) & 0xF == 2
else:
return os.path.isdir(path)
except OSError:
return False