Disk corruption on Portenta

Hi, I’m registering a log file of my application using file.write() across my program. Occasionally, I find damaged files and folders like this in my folder though:

There’s a lot happening in my application but here’s essentially how I’m recording logs in my program:

import pyb, uos

# Datetime from RTC
rtc = pyb.RTC()

# Paths
save_path = "save"
log_path = "log"

# Create folders if does not exist
paths = [save_path, log_path]
for path in paths:
    if path not in uos.listdir():
        uos.mkdir(path)

# Create log file if does not exist
if "log.csv" not in uos.listdir(log_path):
    with open(f"{log_path}/log.csv", "a") as file:
        file.write("timestamp, event\n")
        file.close()

# Create log/last_bait_dispense file if does not exist
if "bait_log.csv" not in uos.listdir(log_path):
    with open(f"{log_path}/bait_log.csv", "a") as file:
        file.write("timestamp\n")
        file.close()

# Reformat datetime
def dt_format():
    return "_".join(str(i) for i in rtc.datetime()[0:3]+rtc.datetime()[4:7])

# Register general event logs
def logprog(event):
    with open(f"{log_path}/log.csv", "a") as file:
        if event == "Motion":
            file.write(f"\n{dt_format()}, {event}\n")
        else:
            file.write(f"{dt_format()}, {event}\n")
        file.close()
    print(event)
    pyb.delay(250)

# Register latest bait drop datetime (replace if already existing)
def bait_log():
    with open(f"{log_path}/bait_log.csv", "w") as file:
        file.write(f"{rtc.datetime()}\n")
        file.close()
        pyb.delay(250)
        
while True:
    logprog("Motion")
    pyb.delay(5000)
    logprog("Animal detected, bait dropped")
    bait_log()
    pyb.delay(10000)

Is there a way I can avoid this?

Regards,

PC

Hi, those are disk corruption events. They are happening because power is lost while writing data.

Do you have a way to power off the device safely?

Thanks for responding, Kwabena.

My system is battery powered and I’m using ATtiny85 to deepsleep and save power. The Portenta sends a HIGH signal to make this happen. Disk corruption could happen at any point I suspect when the battery voltage is insufficient (?)

PC

If the portenta safely shuts down, then it shouldn’t happen. If it doesn’t shut down safely, then it will.