[clug] Python Golf time

Andrew Janke a.janke at gmail.com
Fri Apr 8 03:44:45 UTC 2016


Egads, you win the prize of making Python look the most like Perl, it
looks beautiful.  Others would disagree.  For now I still have this
and might stick with it despite yours working!

   for root, dirs, files in os.walk(os.path.join(indir), topdown=True):
        for f in files:
            if f.endswith(".txt"):
                first_file = os.path.join(root, f)
                break

I think I can claim that mine is faster as I don't go through the
whole list and simply bomb when I have one via break. This might be
untrue depending on how the internals of python work determining
"files".  ie: Does it just get the whole thing or does it buffer it.


a

On 8 April 2016 at 13:36, Peter Barker <pbarker at barker.dropbear.id.au> wrote:
> On Fri, 8 Apr 2016, Peter Barker wrote:
>
>>> Shortest way to find the first file in a directory tree.
>>
>> filter(lambda x : x.endswith('.txt'), os.listdir("/tmp"))[0]
>>>
>>> (the above of course only deals with one directory level)
>>
>> As does mine.
>
>
> ... this one does trees:
>
> winner = (filter(lambda j : j.endswith(".TXT"), [ os.path.join(x[0],z) for z
> in  x[2] for x in os.walk("/tmp") ]))[0]
>
> 'though, frankly, I think we all lose with that.
>
>>> a
>
>
> yours,
>
> --
> Peter Barker                          |   Programmer,Sysadmin,Geek.
> pbarker at barker.dropbear.id.au         |   You need a bigger hammer.
> :: It's a hack! Expect underscores! - Nigel Williams



More information about the linux mailing list