3

It's not work fo me:

target_dir = "a/b/c/d/e/"
os.makedirs(target_dir,0777) 

os.chmod work only for last directory ...

Bdfy
  • 23,141
  • 55
  • 131
  • 179

3 Answers3

10

You can use os.walk to traverse directories. (Below not tested, experiment it yourself)

for r, d, f in os.walk(path):
    os.chmod(r, 0o777)
Asclepius
  • 57,944
  • 17
  • 167
  • 143
ghostdog74
  • 327,991
  • 56
  • 259
  • 343
  • Good one! I can confirm that it works for me. The trick is that `topdown` defaults to `True`. I was worried that it would try to walk a directory it doesn't have permission for. – Adrian Ratnapala Apr 28 '13 at 16:56
  • Actually I was wrong - I wasn't testing it properly: it chmods the parent of the directory that it should be chmoding. My answer below really does work for me. – Adrian Ratnapala Apr 28 '13 at 17:20
1

ghostdog74's answer almost works, but it tries to walk into the directory before it chmods it. So the real answer is less elegant:

os.chmod(path , 0o777)
for root,dirs,_ in os.walk(path):
    for d in dirs :
        os.chmod(os.path.join(root,d) , 0o777)
Adrian Ratnapala
  • 5,485
  • 2
  • 29
  • 39
  • I would explicitly chmod them inside the inner loop. Your files normally need different permissions from the directories, so it make sense to do them in two separate lines of code. – Adrian Ratnapala Jan 19 '15 at 14:45
-1

One line version for this is:

list(map(lambda x: os.chmod(x[0], 0o775), os.walk(target_dir)))

It is helpful when you have to use python console to make these changes, probably better to use the more readable for loop version suggested above in production code.

Shubham Chaudhary
  • 47,722
  • 9
  • 78
  • 80