[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: How to find dirs with single item



On Fri, May 30, 2014 at 8:32 AM, Steve Litt <slitt@troubleshooters.com> wrote:
> On Thu, 29 May 2014 14:31:03 -0500
> Dennis Wicks <wix@mgssub.com> wrote:
>
>> Can't quite figure out how to do this.
>>
>> I'd like to be able to scan a Volume or directory and find
>> all directories that have only one item in them. Either
>> directory or file.
>>
>> Any ideas??
>>
>> TIA!
>> Dennis
>
> If you're willing to write a fairly simple Python program it would be
> pretty easy. You could probably even do it with a find piped to sort
> piped to a very simple AWK script.

Challenge accepted :)

import os
for root, dirs, files in os.walk('.'):
    if len(dirs + files) == 1: print(root)

That'll search the current directory and all subdirectories. (Change
the argument to os.walk() to start someplace else.) Should run in any
Python from 2.3 onwards, although I only tested it on 2.7 and 3.5ish.

As long as you have Python 3.x installed, it can be done as a shell one-liner:

rosuav@sikorsky:~/Gypsum$ python3 -c 'import os; [print(r) for r,d,f
in os.walk(".") if len(d+f)==1]'
./.git/info
rosuav@sikorsky:~/Gypsum$ ls -la .git/info
total 12
drwxr-xr-x 2 rosuav rosuav 4096 Feb 20  2013 .
drwxr-xr-x 8 rosuav rosuav 4096 May 30 02:33 ..
-rw-r--r-- 1 rosuav rosuav  240 Feb 20  2013 exclude

(Could be done as a Py2 one-liner, but not as cleanly.)

ChrisA


Reply to: