我试图使用.asm MicroPython在sd卡中读取带有和.py扩展名的所有文件。
我在这个问题中检查了答案,但它们不适用于MicroPython。
MicroPython没有glob或pathlib,在使用os库时尝试以下代码:
for file in os.listdir('/sd'):
filename = os.fsdecode(file)
if filename.endswith(".asm") or filename.endswith(".py"):
print(filename)我得到了这个错误'module' object has no attribute 'fsdecode'
我如何让它与MicroPython一起工作呢?
发布于 2022-02-02 21:34:15
对于一个浅表的listdir来说,您不需要fsdecode,实际上它不是MicroPython os模块的一部分,请记住,MicroPython有一个优化的模块和方法子集。
for filename in os.listdir("/sd"):
if filename.endswith(".asm") or filename.endswith(".py"):
print(filename)实际上,为了避免子文件夹,您应该检查类型,这可以通过使用os.ilistdir找到
for entry in os.ilistdir("/sd"):
# print(entry)
if entry[1] == 0x8000:
filename = entry[0]
if filename.endswith(".asm") or filename.endswith(".py"):
print(filename)发布于 2022-02-02 14:08:47
在正确的轨道上,os.listdir在任何版本的MicroPython上都能正常工作,但不会恢复子文件夹。
因此,您需要将文件夹与文件区分开来,如下所示。
"""Clean all files from flash
use with care ; there is no undo or trashcan
"""
import uos as os
def wipe_dir( path=".",sub=True):
print( "wipe path {}".format(path) )
l = os.listdir(path)
l.sort()
#print(l)
if l != ['']:
for f in l:
child = "{}/{}".format(path, f)
#print(" - "+child)
st = os.stat(child)
if st[0] & 0x4000: # stat.S_IFDIR
if sub:
wipe_dir(child,sub)
try:
os.rmdir(child)
except:
print("Error deleting folder {}".format(child))
else: # File
try:
os.remove(child)
except:
print("Error deleting file {}".format(child))
# wipe_dir(path='/')https://stackoverflow.com/questions/70946767
复制相似问题