in need of some sorting help

Kent Johnson kent at kentsjohnson.com
Thu Mar 2 06:44:07 EST 2006


ianaré wrote:
> Hey all,
> 
> if i use a os.walk() to append files to a list like so...
> 
> files = []
> root = self.path.GetValue() # wx.TextCtrl input
> filter = self.fileType.GetValue().lower()  # wx.TextCtrl input
> not_type = self.not_type.GetValue()  # wx.CheckBox input
> 
> for base, dirs, walk_files in os.walk(root):
>                     main.Update()
>                     # i only need the part of the filename after the
> user selected path:
>                     base = base.replace(root,"")
> 
>                     for entry in walk_files:
>                         entry = os.path.join(base,entry)
>                         if filter != "":
>                             if filter in entry.lower() and not
> not_type:
>                                 files.append(entry)
>                             if filter not in entry.lower() and
> not_type:
>                                 files.append(entry)
>                         else:
>                             files.append(entry)
> 
> ... will it sort properly on mac and *nix? if not, is there a tried an
> true sorting method someone could graciously let me know of?

The lists of files and directories yielded by os.walk() will be in the 
order that the OS returns them from os.listdir(). According to the docs 
this list is in "arbitrary" order.

You can sort the lists yourself. If you modify dirs in place it will 
affect the subsequent walk. So you could use
for base, dirs, walk_files in os.walk(root):
   dirs.sort(key=str.lower) # note no need for lambda
   walk_files.sort(key=str.lower)
   # etc

Kent



More information about the Python-list mailing list