pythonpython-2.7python-3.xpython-os

Is there any equivalent of chgrp -R in python?


I want to change the group name of one directory recursively, I am using os.chown() to do that. But I can not find any recursive flag like (chgrp -R) in os.chown().


Solution

  • I wrote a function to perform chgrp -R

    def chgrp(LOCATION,OWNER,recursive=False):
    
      import os 
      import grp
    
      gid = grp.getgrnam(OWNER).gr_gid
      if recursive:
          if os.path.isdir(LOCATION):
            os.chown(LOCATION,-1,gid)
            for curDir,subDirs,subFiles in os.walk(LOCATION):
              for file in subFiles:
                absPath = os.path.join(curDir,file)
                os.chown(absPath,-1,gid)
              for subDir in subDirs:
                absPath = os.path.join(curDir,subDir)
                os.chown(absPath,-1,gid)
          else:
           os.chown(LOCATION,-1,gid)
      else:
        os.chown(LOCATION,-1,gid)