如何从给定路径中删除..

时间:2019-07-02 04:50:55

标签: python python-3.x

给出了../hello/world/foo.txt../..hello/world/bar.txt的路径,如何使用Python安全地返回hello/world/foo.txthello/world/bar.txt

我只想删除所有带前缀的相对路径引用

../hello/world/foo.txt      => hello/world/foo.txt
../../hello/world/bar.txt   => hello/world/bar.txt
./hello/world/boo.txt       => hello/world/boo.txt
hello/world/moo.txt         => hello/world/moo.txt

4 个答案:

答案 0 :(得分:0)

您可以尝试这样

s = '../../hello/world/bar.txt'
>>> "/".join(i for i in s.split('/') if '.' not in i[0])
'hello/world/bar.txt'

您可以像这样使用os.path.join

>>> os.path.join(*[i for i in s.split('/') if '.' not in i[0]])
'hello\\world\\bar.txt'

答案 1 :(得分:0)

尝试使用此简单的正则表达式:
.表示当前目录 ..表示当前目录正上方的目录。

因此,路径中仅存在...。因此,点.在其后跟/的路径中出现1或2次。正则表达式将为-> r'\.{1,2}/'

>>> string = "../../hello/world/bar.txt"
>>> result = re.sub(r'\.{1,2}/','',string)
>>> print(result)
hello/world/bar.txt

>>> string = ".././hello/world/bar.txt"
>>> result = re.sub(r'\.{1,2}/','',string)
>>> print(result)
hello/world/bar.txt

>>> string = "./hello/world/bar.txt"
>>> result = re.sub(r'\.{1,2}/','',string)
>>> print(result)
hello/world/bar.txt

答案 2 :(得分:0)

您可以使用path.split('..')[-1].strip('.').strip('/')

答案 3 :(得分:0)

我正试图尽可能地便携。

  • 首先使用os.normpath
  • 然后根据os.sep(斜杠/反斜杠)进行拆分
  • 然后过滤出确切当前目录或父目录
  • 的路径部分

像这样:

import os

strings = """../hello/world/foo.txt
../../hello/world/bar.txt
./hello/world/boo.txt
hello/world/moo.txt
hello/world./moo.txt
"""

for p in strings.splitlines():
    print(os.sep.join([x for x in os.path.normpath(p).split(os.sep) if x not in (os.pardir,os.curdir)]))

结果(在Windows上):

hello\world\foo.txt
hello\world\bar.txt
hello\world\boo.txt
hello\world\moo.txt
hello\world.\moo.txt

os.sep.join替换为"/".join,以在所有平台上强制斜杠。

相关问题