Access all classes in a directory, put into an array, and print them out

Tim Hammerquist tim at vegeta.ath.cx
Tue Jul 3 21:14:35 EDT 2001


Alex Martelli <aleaxit at yahoo.com> wrote:
> "Kemp Randy-W18971" <Randy.L.Kemp at motorola.com> wrote in message
> news:mailman.994168205.8845.python-list at python.org...
> > Can anyone share a short code example of how to access all the programs in
> a
> > Unix directory, put them into an array, and print them out in Python?
> Here
> > is the code I have to do it in Perl (please forgive the harsh language).
> >
> > #!/usr/bin/perl -w
> > #use Net::FTP;
> > opendir (TEMP, '/usr2/ecadtesting/javaprograms')
> >   or die "Can't open current directory.";
> > @files=join(',',grep(!/^\.\.?$/, readdir TEMP));
> > closedir TEMP;
> > print "\n";
> > print @files;
> > print "\n";
> 
> #!/usr/bin/python
> import os
> print os.listdir('/usr2/ecadtesting/javaprograms')
> 
> Makes you wonder where Perl got its reputation for
> conciseness, doesn't it?-)  [Note the . and .. entries
> are automatically removed by the listdir function].

A more concise Perl example would be:

    #!/usr/bin/perl -w
    sub listdir {
        opendir DIR, $_[0] or die $!;
        @files = grep { !/^\.\.?$/ } readdir DIR;
        close DIR;
        @files;
    }
    print join ',', listdir('/usr2/ecadtesting/javaprograms');

Someone had to package the code to open/read/close a directory in the
os.listdir function, right? =)

There is, undoubtedly, a Perl module that's already simplified this.

People are just as capable of writing bad Perl code as they are of
writing bad Python code.  You've heard of people writing this?

    for i in range(len(array)):
        process(array[i])

Of course, once you know a little more it becomes:

    for item in array:
        process(item)

or

    map(process, array)

etc.

=)
-- 
-Tim Hammerquist <timmy at cpan.org>

Any emotion, if it is sincere, is involuntary.
    -- Mark Twain



More information about the Python-list mailing list