1

I have this snippet of code that looks like this:

server_directory = "/Users/storm/server"
def get_directory(self, username):
    home = server_directory + "/" + username
    typic = os.getcwd()
    if typic == server_directory:
        return "/"
    elif typic == home:
        return "~"
    else:
        return typic

And every-time I change the directory out of the two nice server directory and home directory of the user, it would look like /Users/storm/server/svr_user. How do I make it /svr_user2 instead of /Users/storm/server/svr_user, since I would like to emulate a home directory and a virtual "root" directory?

1
  • 1
    As was mentioned in your other question, check out os.path Commented Feb 15, 2013 at 10:36

2 Answers 2

4

Although you can do a lot with string manipulation, a better way would be using os.path:

import os

src = '/Users/storm/server/svr_user'
dst = '/svr_user2'

a = '/Users/storm/server/svr_user/x/y/z'
os.path.join(dst, os.path.relpath(a, src))

returns

'/svr_user2/x/y/z'
Sign up to request clarification or add additional context in comments.

Comments

0

The not so politically correct alternative of eumiro's answer would be:

import re

src = '/Users/storm/server/svr_user'
dst = '/svr_user2'

a = '/Users/storm/server/svr_user/x/y/z'
re.sub(src, dst, a, 1)

Which yields:

'/svr_user2/x/y/z'

Notice the 1 which means replace once.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.