helpmelearn
helpmelearn

Reputation: 381

Python: How to do this string manipulation

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/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!

Upvotes: 1

Views: 301

Answers (3)

Phil Hunt
Phil Hunt

Reputation: 527

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.

Upvotes: 1

Fred Foo
Fred Foo

Reputation: 363487

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)

Upvotes: 2

Greg Hewgill
Greg Hewgill

Reputation: 992707

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']

Upvotes: 3

Related Questions