views:

339

answers:

5

What's the "python way" to recursively set the owner and group to files in a directory? I could just pass a 'chown -R' command to shell, but I feel like I'm missing something obvious.

I'm mucking about with this:


import os  
path = "/tmp/foo"  
for root, dirs, files in os.walk(path):  
  for momo in dirs:  
    os.chown(momo, 502, 20)

This seems to work for setting the directory, but fails when applied to files. I suspect the files are not getting the whole path, so chown fails since it can't find the files. The error is:

'OSError: [Errno 2] No such file or directory: 'foo.html'

What am I overlooking here?

+2  A: 

glob.iglob is a much simpler way to get a set of paths recursively to then iterate over.

Amber
No, glob is not infinitely recursive.
too much php
+3  A: 

try os.path.join(root,momo) that will give you full path

Kugel
+1  A: 

Don't forget the for f in files loop, either. Similarly, remember to os.path.join(root, f) to get the full path.

dash-tom-bang
+2  A: 
import os  
path = "/tmp/foo"  
for root, dirs, files in os.walk(path):  
  for momo in dirs:  
    os.chown(momo, 502, 20)
  for file in files:
     fname = os.path.join(root, file)
     os.chown(fname, aaa, bb)

substitute aaa and bb as you please

Arrieta
+3  A: 

The dirs and files lists are all always relative to root - i.e., they are the basename() of the files/folders, i.e. they don't have a / in them (or \ on windows). You need to join the dirs/files to root to get their whole path if you want your code to work to infinite levels of recursion:

import os  
path = "/tmp/foo"  
for root, dirs, files in os.walk(path):  
  for momo in dirs:  
    os.chown(os.path.join(root, momo), 502, 20)
  for momo in files:
    os.chown(os.path.join(root, momo), 502, 20)

I'm suprised the shutil module doesn't have a function for this.

too much php
Thanks, this was helpful -- Thanks to everyone else was well!
Geoff