Listing files in a directory via python
I’ve come across a few situations where batch processing of snapshots
is necessary. Normally I manually key in the number of snaps in the
for loop, but is there a better more python way? Of course there is!
Enter ‘glob‘. Glob is
basically a wrapper for os.listdir, which is equivalent to typing ‘ls
-U’ in terminal. If you use the -U however, the ordering is completely
arbitrary, so by using say:
import glob
snaps = glob.glob("snapshot\_\*")
You’re going to get an unsorted back. For some this may not be a
problem, but for me? I usually need a list ordered 000-N! The solution
for this comes in the form of the the python function
sorted():
import glob
import os
snaps = sorted(glob.glob("snapshot\_\*"), key=os.path.relpath)
which returns a sorted list! The key (pun intended) here is the key
keyword, which tells it which os path to sort by. Many options exist
such as ‘os.path.getmtime’ to sort by timestamp, and ‘os.path.getsize’
to sort by size. Thanks to
stackoverflow
again for the assistance!