473,396 Members | 1,892 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

sort by file/directory

I have a list that includes files and directories

ie: list = ['file', 'file2', 'dir1','file3','dir2' ]

I want to sort it so it looks like this

['dir1', 'dir2', 'file1','file2','file3' ]
I'm just wondering if there is an easy way to do this

Thanks
Mike
Jul 18 '05 #1
3 9322
Mike Zupan wrote:

I have a list that includes files and directories

ie: list = ['file', 'file2', 'dir1','file3','dir2' ]

I want to sort it so it looks like this

['dir1', 'dir2', 'file1','file2','file3' ]

I'm just wondering if there is an easy way to do this


For the above list, executing .sort() would give the correct
result, but presumably you meant for this to work in a more
general manner.

Here's one way to do it, using the Decorate-Sort-Undecorate
pattern that should be familiar to all Python programmers:

(Untested code... likely to have various small errors, left
as an exercise for the reader. :-)

# best to avoid using the name "list" as it conflicts with
# a name in the built-in module
names = [ fill in your own data here ]

import os
sortme = []
for name in names:
# only works if names are absolute, or in current directory
# you probably have some other way to tell whether
# something is a folder, but the key thing is to
# form a tuple with 0 for directories, 1 for files, then
# the name
sortme.append((not os.path.isdir(name), name))

sortme.sort() # in-place sort, of course!

# remove "decoration" which forced the sort to put directories
# first, leaving just the names
names = [item[1] for item in sortme]

-Peter
Jul 18 '05 #2
* Mike Zupan (mz****@meso.com) wrote:
I have a list that includes files and directories

ie: list = ['file', 'file2', 'dir1','file3','dir2' ]

I want to sort it so it looks like this

['dir1', 'dir2', 'file1','file2','file3' ]
I'm just wondering if there is an easy way to do this


Is there anything in the name of the files/directories that specified that
it is a file or a directory? If not, then I wouldn't think so. When you
are gathering the file and directory listing (maybe you're using os.walk?),
then you could at that time do something like (given a 'dir_list' and a
'file_list'):
if os.path.isdir(path_to_file): .... dir_list.append(os.path.basename(path_to_file))
.... else:
.... file_list.append(os.path.basename(path_to_file))

Then sort the lists and concatenate them together:
dir_list.sort()
file_list.sort()
new_list = dir_list + file_list
new_list

['bin', 'etc', 'sbin', 'tmp', '.muttrc', 'htpasswd', 'httpd.conf',
'passwd']
Jeremy Jones

Jul 18 '05 #3
>>>>> "Mike" == Mike Zupan <mz****@meso.com> writes:

Mike> I have a list that includes files and directories ie: list =
Mike> ['file', 'file2', 'dir1','file3','dir2' ]

Mike> I want to sort it so it looks like this

Mike> ['dir1', 'dir2', 'file1','file2','file3' ]
Mike> I'm just wondering if there is an easy way to do this
This is a good example of when you should use the decorate, sort,
undecorate (DSU) pattern. When python sorts tuples, it compares first
on the first element of the tuple and then on the next element, and
then so on. If you create tuples where the first element of dirs
compares less than the first element of files, and the second element
is just the dir/file name, then you'll get the sort you want. All you
have have to do is undecorate, ie, remove the unwanted information
from the tuples. Here is the approach

import os
fnames = ('emacs', '.emacs', 'tex','.tcshrc','diary' )

tmp = [ (not os.path.isdir(fname), fname) for fname in fnames] # decorate
tmp.sort() # sort
fnamesSorted = [fname for isdir, fname in tmp] # undecorate

For more info on DSU, see
http://groups.google.com/groups?num=...=Google+Search
and the Python Cookbook, which has a chapter on sorting mainly devoted
to DSU.

Mike> list = ['file', 'file2', 'dir1','file3','dir2' ]

You may want to avoid the name list because it is a built-in. For
example, to convert a string to a list of characters, you would do

seq = list('John Hunter')

After creating a variable named list, you can no longer do this.
Cheers,
John Hunter

Jul 18 '05 #4

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

Similar topics

2
by: vince | last post by:
MSDN help says you can use a UNC path for any methods that accept a path, and I'm wondering if I can also substitute an IP address for the UNC....??? Example: Using System.IO.File.Move() ...
1
by: Maurice Mertens | last post by:
Hi all, is it possible to programmatically determine the current users permissions on a file / directory? I want to check if the user can add/delete files to a folder. -- Met vriendelijke...
5
by: Aryeh Katz | last post by:
I'd like to set the permissions on a file (directory) so that a user (and only that user) is granted full control for that file. Using c++, I was able to use the BuildExplicitAccessWithName, and...
0
by: Ollie Riches | last post by:
I am executing a DTS programmatically from C# using COM interop. Is it possible to set the 'script file directory' from the C# code? For anyone else you gets an 'Access Denied Error' when...
2
by: Antonio-F100 | last post by:
Hello, I need help creating the code for a macro button on a form that will open a file directory with windows explorer. I have about 500 directories with very long names and only want to...
4
by: samjnaa | last post by:
Please check for sanity and approve for posting at python-dev. Currently file-directory-related functionality in the Python standard library is scattered among various modules such as shutil, os,...
5
by: peruron | last post by:
Hello again! I've been discussing the advantages of Python over C-Shell. I was asked if I can replace the use of "grep" in searching for a specific string in a multi-file directory - I have to go...
7
by: anupkkumar | last post by:
Hi All, Is there any way to copy a file/ directory from one location to the other? The file or the directory name should be given by the user. This is the criteria. For example:...
1
by: ateale | last post by:
Hi Guys, I am using ruby on rails trying to develop a basic cms/dam for our company. The work we do is post production for television commercials. Each tv commercial we do broken down into...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.