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?

4

2 に答える 2

4

文字列操作で多くのことができますが、より良い方法は以下を使用すること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))

戻り値

'/svr_user2/x/y/z'
于 2013-02-15T10:38:55.987 に答える
0

euiroの答えの政治的に正しくない代替案は次のようになります。

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)

どちらが得られますか:

'/svr_user2/x/y/z'

1は一度置換することを意味することに注意してください。

于 2013-02-15T10:49:17.753 に答える