1

我有如下代码片段:

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

每次我从两个不错的服务器目录和用户的主目录中更改目录时,它看起来像/Users/storm/server/svr_user. 由于我想模拟主目录和虚拟“根”目录,我该如何制作它/svr_user2而不是?/Users/storm/server/svr_user

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

eumiro 的答案在政治上不太正确的替代方案是:

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 回答