473,785 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 9344
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(n ame), 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.co m) 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(p ath_to_file): .... dir_list.append (os.path.basena me(path_to_file ))
.... else:
.... file_list.appen d(os.path.basen ame(path_to_fil e))

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.co m> 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(f name), 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
3499
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() File.Move("\\\\MyServer\\share\\dir\\myfile.txt", "\\\\YourServer\\share\\dir\\myfile.txt");
1
1470
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 groet / With regards / Saludos, Moviat Automatisering
5
2806
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 SetEntriesInAcl calls. Is there a native c# way to do this? Aryeh
0
1399
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 attempting to run a DTS package from code it is because the local machine attempting to run the remote DTS package does not have the 'script file directory' defined on the local machine. Cheers
2
3105
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 input part of the directory name into the table that the form uses.
4
1428
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, dircache etc. So I request that the functions be gathered and consolidated at one place. Some may need renaming to avoid conflicts or for clarification.
5
2590
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 through all the files, and find all the occurrences of a specific string. Can anyone suggest an idea? Thanks!
7
2632
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: My.Computer.FileSystem.CopyDirectory("C:\abc\<file/dir>", "D:\cde\<File/dir>") Here the file/dir should be obtained from the user during runtime. Please let me know the code or the logic. Thanks,
1
2915
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 'shots' (or edit), and each shot usually goes through multiple versions/iterations. And lastly each of these shots incorporates elements from 2d and 3d artists - each having multiple versions. What I want to do is find a way for artists/clients to be...
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9484
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
10350
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
10097
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,...
0
9957
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6742
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
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5518
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2887
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.