Author: tlinnet Date: Wed Sep 3 22:50:46 2014 New Revision: 25609 URL: http://svn.gna.org/viewcvs/relax?rev=25609&view=rev Log: Added function to lib.io to sort a list of filenames into human-understandable alphanumeric order. Modified: trunk/lib/io.py Modified: trunk/lib/io.py URL: http://svn.gna.org/viewcvs/relax/trunk/lib/io.py?rev=25609&r1=25608&r2=25609&view=diff ============================================================================== --- trunk/lib/io.py (original) +++ trunk/lib/io.py Wed Sep 3 22:50:46 2014 @@ -37,7 +37,7 @@ from os import devnull from os import F_OK, X_OK, access, altsep, getenv, makedirs, pathsep, remove, sep from os.path import expanduser, basename, splitext, isfile -from re import search +from re import search, split from sys import stdin, stdout, stderr from warnings import warn @@ -480,6 +480,31 @@ return file_obj +def sort_filenames(filenames=None, rev=False): + """Sort the given list in alphanumeric order. Should be equivalent to unix 'ls -n' command. + + @keyword filenames: The list of filenames + @type l: list of strings + @keyword rev: Flag, if the list should be reverted + @type rev: boold + """ + + # Define function to convert to integers if text is digit. + convert = lambda text: int(text) if text.isdigit() else text + + # Define function to create key for sorting. + alphanum_key = lambda key: [ convert(c) for c in split('([0-9]+)', key) ] + + # Now sort according to key. + filenames.sort( key=alphanum_key ) + + # Reverse the list if needed. + if rev: + return reversed(filenames) + else: + return filenames + + def strip(data, comments=True): """Remove all comment and empty lines from the file data structure.