Make paths pick versions automatically

Hi,

Once ina a while I have a directory structure like

dir/v1/file.json
dir/v2/file.json
dir/v3/file.json

and I want to build the path using the lastest version. It would be convenient to have smarter Path objects such that:

lastest = Path('dir/{LATEST_BY_NAME}/file.json')

picks v3.

Cheers.

I wouldn’t pick it, but as well as reusing the syntax for f-string and format string fields, technically that placeholder is a perfectly valid directory name already:

debian@...:~$ ls /tmp/dir -la
total 12
drwxrwxr-x  3 debian debian 4096 Jan 16 13:36 .
drwxrwxrwt 10 root   root   4096 Jan 16 13:36 ..
drwxrwxr-x  2 debian debian 4096 Jan 16 13:36 {LATEST_BY_NAME}

Have you tried something like?:

subdirs = [p for p in Path('dir').iterdir() if p.is_dir()]
latest = max(subdirs, key = lambda p: p.name)
1 Like

This is hard to add to python as the rules for a version name and their comparison are not always obvious.
Consider these two.

dir/v10/file.json
dir/v2/file.json

A simple compare will pick v2 as higher the v10.

dir/v1/file.json
dir/V2/file.json

And here lower v is higher the uppper v so a simple compare will pick v1 not V2.

So the key function needs to be defined more carefully than Path.name, to convert digits to an int.

Also, pathlib already does text pattern matching (albeit without full Regex capture objects). Doesn’t Path('.').glob('dir/v*/file.json') return all the required files?