0

In python I can easily list files in a directory with os.listdir('dir') but how could I easily filter those files to those which belong to a specific group? This is simply done in unix with find . -group "foo"

For example, let's say I have the following three files:

-rwxrwxrwx 1 foo foo 0 Sep 15 08:57 foo.txt
-rwxrwxrwx 1 bar bar 0 Sep 15 08:34 bar.txt
-rwxrwxrwx 1 foo foo 0 Sep 15 08:57 faz.txt

How can I get only those files which belong to the 'group' foo using python?

The files returned should be foo.txt and faz.txt ideally in a list object.

This similar question addresses how to get the group/user after you know the file. I want to filter the list to only a specific group.

Community
  • 1
  • 1
cdeterman
  • 19,630
  • 7
  • 76
  • 100
  • 2
    possible duplicate of [How to get the owner and group of a folder with Python on a Linux machine?](http://stackoverflow.com/questions/927866/how-to-get-the-owner-and-group-of-a-folder-with-python-on-a-linux-machine) – Łukasz Rogalski Sep 15 '15 at 19:40
  • can't you just split it by \n then by space and filter by value on 2nd position? – m.antkowicz Sep 15 '15 at 19:43

2 Answers2

2

this may work:

import os
import grp
gid = grp.getgrnam('foo').gr_gid

file_list = []
for fle in os.listdir('dir'):
    if os.stat(fle).st_gid == gid:
        file_list.append(fle)

or as a one-liner (list-comprehension):

file_list = [fle for fle in os.listdir('dir') if os.stat(fle).st_gid == gid]
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
0

The grp module comes to your help, together with Python's list comprehensions that are very handy for succintctly filtering arrays.

[f for f in os.listdir("dir") if grp.getgrgid(os.stat(f).st_gid).gr_name == "foo"]

If you are content with just the group id, you can avoid grp altogether:

[f for f in os.listdir("dir") if os.stat(f).st_gid == 1234] 

(Replace, of course, 1234 with the actual group id)

Tobia Tesan
  • 1,938
  • 17
  • 29