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

标签 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

最佳答案

我正在努力使其尽可能便携。

  • 首先使用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 以在所有平台上强制使用斜杠。

关于python - 如何从给定路径中删除 ..,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56845512/

相关文章:

python - Python中的一对一继承

python - 我的脚本在单击链接时遇到错误

python - 无法使用基于 python 的库 ftplib 连接到本地 FTP 服务器

Python 日期时间奇怪的行为

python - for循环在while循环中

python - 从其他表访问数据 - Django Rest Api 中的外键 - 未知列

python - 堆和负数的奇怪行为

python - Spring批处理运行python代码?

python - 带函数注解的装饰器

python - requests.exceptions.ConnectionError : ('Connection aborted.' , gaierror(8, 'nodename nor servname provided, or not known' ))