给定路径 ../hello/world/foo.txt
或 ../..hello/world/bar.txt
,我如何安全地使用 Python 返回 hello/world/foo.txt
或 hello/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/