sort a list of files

G

Gary Wessle

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
 
R

Ryan Forsythe

Gary said:
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]
 
S

Scott David Daniels

Ryan said:
Gary said:
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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top