如何以独立于操作系统的方式规范化/折叠Python中的路径或URL? [英] How can I normalize/collapse paths or URLs in Python in OS independent way?
问题描述
我尝试使用os.normpath
来将http://example.com/a/b/c/../
转换为http://example.com/a/b/
,但是在Windows上它不起作用,因为它确实将斜杠转换为反斜杠.
I tried to use os.normpath
in order to convert http://example.com/a/b/c/../
to http://example.com/a/b/
but it doesn't work on Windows because it does convert the slash to backslash.
推荐答案
此处是操作方法
>>> import urlparse
>>> urlparse.urljoin("ftp://domain.com/a/b/c/d/", "../..")
'ftp://domain.com/a/b/'
>>> urlparse.urljoin("ftp://domain.com/a/b/c/d/e.txt", "../..")
'ftp://domain.com/a/b/'
请记住,urljoin
会一直考虑到最后一个/
的路径/目录-这之后是文件名(如果有的话).
Remember that urljoin
consider a path/directory all until the last /
- after this is the filename, if any.
此外,请勿在第二个参数中添加前导/
,否则您将无法获得预期的结果.
Also, do not add a leading /
to the second parameter, otherwise you will not get the expected result.
os.path
模块取决于平台,但是对于仅使用斜杠而不使用URL的文件路径,可以使用posixpath,normpath
.
os.path
module is platform dependent but for file paths using only slashes but not-URLs you could use posixpath,normpath
.
这篇关于如何以独立于操作系统的方式规范化/折叠Python中的路径或URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!