Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python way for recursively setting file permissions?

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?

like image 375
Geoff Avatar asked May 17 '10 23:05

Geoff


People also ask

How do I set recursive permissions?

The chmod command with the -R options allows you to recursively change the file's permissions. To recursively set permissions of files based on their type, use chmod in combination with the find command.

How do I set 777 recursively?

If you are going for a console command it would be: chmod -R 777 /www/store . The -R (or --recursive ) options make it recursive.

Is chmod recursive?

Changing permissions with chmod It can be used for individual files or it can be run recursively with the -R option to change permissions for all of the subdirectories and files within a directory.

How do I change folder permissions recursively?

You can change permissions of files using numeric or symbolic mode with the chmod command. Use the chmod command with the R (recursive) option to work on all directories and files under a given directory. The permissions of a file can be changed only with the user with sudo priviledges, or the file owner.


1 Answers

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.

like image 133
too much php Avatar answered Sep 21 '22 03:09

too much php