Python 递归设置文件权限的方法是什么?
递归地将所有者和组设置为目录中文件的“python 方式”是什么?我可以将“chown -R”命令传递给 shell,但我觉得我遗漏了一些明显的东西。
我正在对此进行思考:
import os
path = "/tmp/foo"
for root, dirs, files in os.walk(path):
for momo in dirs:
os.chown(momo, 502, 20)
这似乎适用于设置目录,但应用于文件时会失败。我怀疑这些文件没有获取整个路径,因此 chown 失败,因为它找不到文件。错误是:
'OSError:[Errno 2]没有这样的文件或目录:'foo.html'
我在这里忽略了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
dirs
和files
列表总是相对于root
- 即,它们是根目录的basename()
文件/文件夹,即它们中没有/
(或 Windows 上的\
)。如果您希望代码能够无限级递归,则需要将目录/文件连接到 root 以获得它们的完整路径:令人惊讶的是,shutil 模块并不这样做有这个功能。
The
dirs
andfiles
lists are all always relative toroot
- i.e., they are thebasename()
of the files/folders, i.e. they don't have a/
in them (or\
on windows). You need to join the dirs/files toroot
to get their whole path if you want your code to work to infinite levels of recursion:Surprisingly, the
shutil
module doesn't have a function for this.正如上面正确指出的那样,接受的答案错过了顶级文件和目录。其他答案使用 os.walk ,然后循环遍历 dirnames 和 filenames 。但是,
os.walk
无论如何都会遍历dirnames
,因此您可以跳过dirnames
的循环,而只需chown
当前目录(dirpath
):As correctly pointed out above, the accepted answer misses top-level files and directories. The other answers use
os.walk
then loop throughdirnames
andfilenames
. However,os.walk
goes throughdirnames
anyway, so you can skip looping throughdirnames
and justchown
the current directory (dirpath
):这是最简单的方法,并且有点迷失在问题中,所以为了清楚起见,如果您不关心 Windows,您可以在一行中执行此操作:
This is the simplest way, and gets lost in the question a bit, so just for clarity, you can do this in one line if you don't care about Windows:
根据需要替换
aaa
和bb
substitute
aaa
andbb
as you please尝试 os.path.join(root,momo) 这将为您提供完整路径
try
os.path.join(root,momo)
that will give you full path这是我编写的一个函数,它使用 glob 递归地列出文件并更改其权限。
它并不完美,但让我到达了我需要的地方
Here is a function i wrote that uses glob to recursively list files and change their permissions.
it's not perfect, but got me where I needed to be
接受的答案错过了顶级文件。这实际上相当于 chown -R。
The accepted answer misses top level files. This is the actual equivalent of
chown -R
.也不要忘记
for f in files
循环。同样,请记住使用 os.path.join(root, f) 来获取完整路径。Don't forget the
for f in files
loop, either. Similarly, remember toos.path.join(root, f)
to get the full path.使用
os.lchown
而不是os.chown
来更改链接本身和文件。use
os.lchown
instead ofos.chown
for changing link themselves and files together.