递归设置文件权限的Python方法是什么? [英] What is the Python way for recursively setting file permissions?

查看:71
本文介绍了递归设置文件权限的Python方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

递归设置目录中文件的所有者和组的python方式"是什么?我可以将chown -R"命令传递给 shell,但我觉得我错过了一些明显的东西.

我正在纠结这个:

<预><代码>导入操作系统路径 = "/tmp/foo"对于 os.walk(path) 中的根、目录、文件:对于目录中的 momo:os.chown(momo, 502, 20)

这似乎适用于设置目录,但应用于文件时失败.我怀疑文件没有得到整个路径,所以 chown 失败,因为它找不到文件.错误是:

'OSError: [Errno 2] 没有那个文件或目录:'foo.html'

我在这里俯瞰什么?

解决方案

dirsfiles 列表总是相对于 root -即,它们是文件/文件夹的 basename(),即它们中没有 /(或 Windows 上的 \).如果您希望代码在无限递归级别上工作,则需要将目录/文件加入 root 以获取它们的整个路径:

import os路径 = "/tmp/foo"对于 os.walk(path) 中的根、目录、文件:对于目录中的 momo:os.chown(os.path.join(root, momo), 502, 20)对于文件中的 momo:os.chown(os.path.join(root, momo), 502, 20)

我很惊讶 shutil 模块没有这个功能.

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?

解决方案

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.

这篇关于递归设置文件权限的Python方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆