开发者

Python: How to do this string manipulation

开发者 https://www.devze.com 2023-02-20 11:05 出处:网络
Folks, Might find this on searching, but need this rather quickly done: I have the path like this: /mnt/path1/path2/path3/

Folks, Might find this on searching, but need this rather quickly done:

I have the path like this: /mnt/path1/path2/path3/

I need to chown all the directories such as /mnt, /mnt/path1, /mnt/开发者_JAVA技巧path1/path2, /mnt/path1/path2/path3, how to get this done in python?

I cannot do 'chown -R /mnt/' since it tries to chown all the files/directories that exist beneath path3, but I wish to chown only upto path3 here for example.

Thank you for any suggestions!


You could do something like this:

>>> import os
>>> path = "abc/def/ghi"
>>> a = path.split("/")
>>> [os.path.join(*a[:i]) for i in range(1, len(a)+1)]
['abc', 'abc/def', 'abc/def/ghi']


Quick 'n' dirty:

stop = '/mnt/path1/path2/path3'
for (dir, subdirs, files) in os.walk('/mnt'):
    if dir[:len(stop)] != stop:
        for x in [os.path.join(dir, f) for f in files] + [dir]:
           os.chown(x, uid, gid)


You need to use the os.path library. If you start off with directory d then os.path.abspath(os.path.join(d, '..')) will return that directory's parent. You do this until you get to /mnt, for each directory running chown on it.

0

精彩评论

暂无评论...
验证码 换一张
取 消