470,841 Members | 1,078 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,841 developers. It's quick & easy.

sort a list of files

Hi

I am trying to print out the contents of a directory, sorted.

**************** the code ****************
1 import os, sys
2
3 if len(sys.argv) < 2:
4 sys.exit("please enter a suitable directory.")
5
6 print os.listdir(sys.argv[1]).sort()
************************************************** **************

if I remove ".sort()" at the end of line 6 I get an unsorted list of
files, if I leave it I get None. who do I fix this?

thank you
May 6 '06 #1
2 1501
Gary Wessle wrote:
Hi

I am trying to print out the contents of a directory, sorted. .... if I remove ".sort()" at the end of line 6 I get an unsorted list of
files, if I leave it I get None. who do I fix this?


`blah.sort()` sorts in-place and returns None. You probably want
sorted(blah):
a = [3, 1, 4, 1, 5, 9]
sorted(a) [1, 1, 3, 4, 5, 9] a [3, 1, 4, 1, 5, 9] a.sort()
a

[1, 1, 3, 4, 5, 9]

--
Ryan Forsythe
May 6 '06 #2
Ryan Forsythe wrote:
Gary Wessle wrote:
Hi

I am trying to print out the contents of a directory, sorted.

...
if I remove ".sort()" at the end of line 6 I get an unsorted list of
files, if I leave it I get None. who do I fix this?


`blah.sort()` sorts in-place and returns None. You probably want
sorted(blah):
>>> a = [3, 1, 4, 1, 5, 9]
>>> sorted(a) [1, 1, 3, 4, 5, 9] >>> a [3, 1, 4, 1, 5, 9] >>> a.sort()
>>> a

[1, 1, 3, 4, 5, 9]


If you are using an old version of Python (2.3.X or before),
the you just need to break your statement up:
Instead of:
6 print os.listdir(sys.argv[1]).sort()
use:
6 files = os.listdir(sys.argv[1])
7 files.sort()
8 print files

--Scott David Daniels
sc***********@acm.org
May 6 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Mike Zupan | last post: by
2 posts views Thread by Jean-Paul Lauque | last post: by
4 posts views Thread by Hrvoje Vrbanc | last post: by
10 posts views Thread by Amit | last post: by
48 posts views Thread by Alex Chudnovsky | last post: by
4 posts views Thread by rn5a | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.