473,657 Members | 2,496 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

in need of some sorting help

Hey all,

if i use a os.walk() to append files to a list like so...

files = []
root = self.path.GetVa lue() # wx.TextCtrl input
filter = self.fileType.G etValue().lower () # wx.TextCtrl input
not_type = self.not_type.G etValue() # 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(ro ot,"")

for entry in walk_files:
entry = os.path.join(ba se,entry)
if filter != "":
if filter in entry.lower() and not
not_type:
files.append(en try)
if filter not in entry.lower() and
not_type:
files.append(en try)
else:
files.append(en try)

.... 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?
oh by sort properly i mean:
file1.ext
file2.ext
file3.ext
file4.ext
zzfile.ext
folder1\file1.e xt
folder1\file2.e xt
folder1\file3.e xt
folder2\file1.e xt
folder2\file2.e xt
folder2\file3.e xt
something tells me it's probably better to do my own sorting, just in
case, so i tried:

files.sort(key= lambda x: x.lower())

but that didn't work, made them out of order.

TIA

Mar 2 '06 #1
8 1557
ianaré wrote:
Hey all,

if i use a os.walk() to append files to a list like so...

files = []
root = self.path.GetVa lue() # wx.TextCtrl input
filter = self.fileType.G etValue().lower () # wx.TextCtrl input
not_type = self.not_type.G etValue() # 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(ro ot,"")

for entry in walk_files:
entry = os.path.join(ba se,entry)
if filter != "":
if filter in entry.lower() and not
not_type:
files.append(en try)
if filter not in entry.lower() and
not_type:
files.append(en try)
else:
files.append(en try)

... 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=s tr.lower) # note no need for lambda
walk_files.sort (key=str.lower)
# etc

Kent
Mar 2 '06 #2
Kent Johnson wrote:
dirs.sort(key=s tr.lower)*#*not e*no*need*for*l ambda


However, this will raise a TypeError for unicode directory names while the
lambda continues to work.

Peter

Mar 2 '06 #3
thank you for the help, i didn't know you could sort in place like
that. definitly will come in handy.
However, i need the sorting done after the walk, due to the way the
application works... should have specified that, sorry.

TIA

Mar 2 '06 #4
ianaré wrote:
However, i need the sorting done after the walk, due to the way the
application works... should have specified that, sorry.

If your desired output is just a sorted list of files, there is no good
reason that you shouldn't be able sort in place. Unless your app is
doing something extremely funky, in which case this should do it:

root = self.path.GetVa lue() # wx.TextCtrl input
filter = self.fileType.G etValue().lower () # wx.TextCtrl input
not_type = self.not_type.G etValue() # wx.CheckBox input

matched_paths = {}
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(ro ot, '')

matched_paths[base] = []
for entry in walk_files:
entry = os.path.join(ba se, entry)
if not filter:
match = True
else:
match = filter in entry.lower()
if not_type:
match = not match
if match:
matched_paths[base].append(entry)

def tolower(x): return x.lower()
files = []
# Combine into flat list, first sorting on base path, then full
path
for base in sorted(matched_ paths, key=tolower):
files.extend(so rted(matched_pa ths[base], key=tolower))

--Ben

Mar 3 '06 #5
arrrg i did it again, not enough explanation... new to asking for
programing help online.
anyway the reason is that the list can be rearanged later in the
program by another function, and i need a way to put it in order
again.. so yes it is doing some pretty funky stuff, lol.
so although your method works well, it would have been problematic for
me to implement a two list system in the app for various reasons. but
you did make me understand a way to sort this thing finally: sort by
base path then by full path, which is how i came up with:

files.sort(key= lambda x: x.lower())
files.sort(key= lambda x: os.path.dirname (x))

well actually i am sorting first by full name, then by base, taking
advantage of python2.4's stable sort().

If you can think of a more efficient (faster) way of doing this please
let me know. i'm not crazy about having to sort this list twice, it can
get pretty big (50,000 entries)

anyway thanks all, this thing had me stuck for over a month !!

Mar 3 '06 #6
ianaré wrote:
you did make me understand a way to sort this thing finally: sort by

base path then by full path, which is how i came up with:

files.sort(key= lambda x: x.lower())
files.sort(key= lambda x: os.path.dirname (x))

well actually i am sorting first by full name, then by base, taking
advantage of python2.4's stable sort().

If you can think of a more efficient (faster) way of doing this please
let me know. i'm not crazy about having to sort this list twice, it can
get pretty big (50,000 entries)


Use a key function that returns a tuple of the two values you want to
sort on:
def make_key(f):
return (os.path.dirnam e(f), f.lower())

files.sort(key= make_key)

Kent
Mar 3 '06 #7
sweet that works great!
thanks again for all the help.

Mar 3 '06 #8
ianaré wrote:
....
files.sort(key= lambda x: x.lower())
files.sort(key= lambda x: os.path.dirname (x))


This is exactly why some of us hate lambda. It encourages
long-way-around thinking.
files.sort(key= lambda x: os.path.dirname (x))

is better written as:
files.sort(key= os.path.dirname )

Learn to have your skin itch when you see:

... lambda name:<expr>(nam e)

And yes, I concede that it _is_ useful in your .lower expression.
It's not that lambda is bad, rather that it seems to encourages
this 'lambda x:f(x)' stuff.

--Scott David Daniels
sc***********@a cm.org
Mar 3 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
10475
by: Al Newton | last post by:
I want to use STL's sort algorithm to sort a string vector. Some of the strings are fairly long (300 to 400 chars) and the vector isn't small (5,000 to 10,000 elements). Naturally, sorting time is long. All I need sorted are the first 10 characters in the strings. Limiting the number of characters processed should speed things up considerably. Is there a way to do 1t? Thanks for any help ... Al
4
2815
by: Gareth Gale | last post by:
I'm trying to implement a way of allowing a user to sort a HTML table via Javascript on the client. I've seen lots of samples where single column sorting (asc or desc) is shown, but I'd like nested sorting i.e. sort by col1 asc, then by col2 desc etc. Can anyone help ?
3
10640
by: google | last post by:
I have a database with four table. In one of the tables, I use about five lookup fields to get populate their dropdown list. I have read that lookup fields are really bad and may cause problems that are hard to find. The main problem I am having right now is that I have a report that is sorted by one of these lookup fields and it only displays the record's ID number. When I add the source table to the query it makes several records...
7
1890
by: ChadDiesel | last post by:
Hello everyone, I'm having a problem with Access that I need some help with. The short version is, I want to print a list of parts and part quantities that belong to a certain part group---One list per page. I created a report that groups the parts by part classification group with a force new page after each group. The report is based on a query of that week's orders. Some of these parts have drawings (usually 2 each stored in an...
1
2636
by: aredo3604gif | last post by:
On Sun, 10 Apr 2005 19:46:32 GMT, aredo3604gif@yahoo.com wrote: >The user can dynamically enter and change the rule connection between >objects. The rule is a "<" and so given two objects: >a < b simply means that b < a can't be set, also it must be a != b. >And with three objects a < b , b < c means a < c > >I studied Quick Union Find algorithms a bit and if I understood them >correctly, once the user gives the input setting the...
4
2192
by: naknak4 | last post by:
Introduction This assignment requires you to develop solutions to the given problem using several different approaches (which actually involves using three different STL containers). You will implement all three techniques as programs. In these programs, as well as solving the problem, you will also measure how long the program takes to run. The programs are worth 80% of the total mark. The final 20% of the marks are awarded for a...
7
1483
by: themastertaylor | last post by:
Hi, I work for a construction company and part of my job is sourcing materials. currently we have a spreadsheet based system whereby each site has a worksheet in the workbook with the standard types of stone in the first column, then across the top we have the main 6 or 7 suppliers and input their price for each material into the grid. I want to develop a system in access basically so that i can search for situations where a supplier...
4
1709
by: access baby | last post by:
i have a huge database based on date and time need to create different report we need to measure our work processes how many order received , order cancelled, completed and count of items completed on or before time. chart or pivot report how do i do that. Please help.
2
3195
by: RajasScripts | last post by:
Hi I need some guidance in sorting HTML input tag sorting.I am able to sort columns with out input tag and with dates.But the only problem is I am not able to sort a column which is text box with Numbers.I am using sorttable.js file which i got from website. This one is working fine with all the column but not with input tag (I mean text box where user enter Numerical value) Regards Raja
0
8326
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8845
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8522
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6177
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5647
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4333
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2745
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1973
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1736
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.