我有这段代码如下:
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
,因为我想模拟主目录和虚拟“根”目录?
答案 0 :(得分: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'
答案 1 :(得分:0)
eumiro's answer的不太政治正确的替代方案是:
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
,这意味着替换一次。