I'm processing some files in a directory and need the files to be sorted numerically. I found some examples on sorting—specifically with using the lambda
pattern—at wiki.python.org, and I put this together:
import re file_names = """ayurveda_1.tif ayurveda_11.tif ayurveda_13.tif ayurveda_2.tif ayurveda_20.tif ayurveda_22.tif""".split('\n') num_re = re.compile('_(\d{1,2})\.') file_names.sort( key=lambda fname: int(num_re.search(fname).group(1)) )
Is there a better way to do this?
In the desktop, click or tap the File Explorer button on the taskbar. Open the folder that contains the files you want to group. Click or tap the Sort by button on the View tab. Select a sort by option on the menu.
How to Sort Files in Windows 10 Numerically and By Size. 1 1. Sort Numerically Using Group Policy Editor. The Group Policy Editor isn't present in the Windows 10 Home edition. You can grab it from reputed ... 2 2. Enable Numeric Sorting Using Registry Editor. 3 3. Sort Folders in Windows 10 by Size. 4 4. TreeSize.
The numerical sorting order takes the sequence of digit occurrence into consideration. In simpler terms, it arranges the files by following the historical value of the first digit, second digit and so on. That's why 11, 12, and 22 file names are appearing between 1 and 3. 2. Enable Numeric Sorting Using Registry Editor Let's test another method.
When you see the Windows Components folder, double-click on it. Scroll down to find the File Explorer folder and open it. You should see a bunch of files here. Find 'Turn off numerical sorting in File Explorer' here and open it. Warning: Don’t mess around with other files in this pane as it can break the way your Windows functions.
If you have files beginning with numbers like 1,2,3, etc., you cannot sort them in ascending or descending order. This is how it is looking currently. You will have to enable numeric sorting in Windows 10 because it is not enabled by default. Duh. To begin, press the Windows Key+R on your keyboard to launch the Run command prompt.
This is called "natural sorting" or "human sorting" (as opposed to lexicographical sorting, which is the default). Ned B wrote up a quick version of one.
import re def tryint(s): try: return int(s) except: return s def alphanum_key(s): """ Turn a string into a list of string and number chunks. "z23a" -> ["z", 23, "a"] """ return [ tryint(c) for c in re.split('([0-9]+)', s) ] def sort_nicely(l): """ Sort the given list in the way that humans expect. """ l.sort(key=alphanum_key)
It's similar to what you're doing, but perhaps a bit more generalized.
Just use :
tiffFiles.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)])
is faster than use try/except.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With