Page 1 of 1

Incremental file name system

Posted: Wed Apr 13, 2022 3:38 pm
by mike317537
Sorry if this is a really simple question, I am very much a beginner at this. I am a mechanical engineer and I am trying to use a Pi Pico as a simple(& cheap) data logger.

I want to create an incremental file name system.

Stack overflow lead me to this https://stackoverflow.com/questions/179 ... -in-python
And this simple script:

import os

i = 0
while os.path.exists("sample%s.xml" % i):
i += 1

fh = open("sample%s.xml" % i, "w")

The os library on the Pi Pico doesn’t appear to contain the same set as a full python library and therefore I just get errors.

Could somebody please tell me how I can load these commands to the Pico or is there a better solution somebody could suggest?

Re: Incremental file name system

Posted: Wed Apr 13, 2022 4:21 pm
by Roberthh
you can use os.stat to check, whether a file exists. os.stat raises an error if not. or you can create a directory list with os.listdir and test, whether a name is in that list.

Re: Incremental file name system

Posted: Thu Apr 14, 2022 12:26 am
by scruss
Try something like this:

Code: Select all

import os


def new_file(base, ext):
    # returns the lowest version of base%03d.ext that doesn't yet exist
    version = 0
    while True:
        filename = "%s%03d.%s" % (base, version, ext)
        try:
            result = os.stat(filename)
        except:
            # stat fails if filename doesn't exist
            return(filename)
        else:
            version = version+1


# rough example code - untested in MicroPython
outfile = new_file("sample", "xml")
print("New file is:", outfile)
fh = open(outfile, "w")
fh.close()
This gives me "New file is: sample000.xml" on the first run, then "New file is: sample001.xml" and so on.

MicroPython docs live here: https://docs.micropython.org/en/v1.18/

Since we're only single-tasking here we don't have to worry about race conditions. And yes, I miss VMS's file versions too: sample.xml;1, sample.xml;2, etc.

Re: Incremental file name system

Posted: Wed Apr 20, 2022 3:19 pm
by mike317537
Thank you
This works! I’m not 100% sure why so I’m going to circle back to this once I’ve captured some data. But I managed to tweak it to do what I want.

I’m new to python (most modern languages if I’m honest last thing I knew what I was doing with was basic on my C64) I am looking at a project for my masters thesis so I have a very steep learning curve coming.

Regards,

Michael