Processing Directory Entries in a Stable Order

Filesystem enumeration need not return a useful sort order. Select a sort key when a result depends on the visitation sequence.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace input order effects
  2. State the comparison rule
  3. Select order with a concrete output comparison
  4. Account for what can change during the walk

Trace input order effects

If a summary keeps the first record for a duplicate ID, processing January before February can retain a different value from the reverse order. Deduplication in source order explains why.

State the comparison rule

Names like part2 and part10 may sort differently by text and by numeric suffix. Choose the promised rule explicitly and include both in a test. Lexicographic versus numeric order gives the comparison.[1]

Select order with a concrete output comparison

A directory containing files r2.txt and r10.txt can enumerate them in either order. A lexical sort places r10 before r2. Sorting by parsed record number places r2 first. Pick the order that the resulting report or build uses. See key functions for ordering.

Raw enumeration might return r2,r10
Lexical: r10,r2
Numeric suffix: r2,r10
Invalid numeric suffix needs a documented outcome

Account for what can change during the walk

Sorting names gives stable ordering for a given name list. It does not make contents an immutable snapshot. If files may change concurrently, decide whether to detect the change or read a designated snapshot. Test names differing by digits and casing under supported platforms.

References

  1. Python Software Foundation, io: Core Tools for Working with Streams ↩