首页 > 解决方案 > 使用 Python 缩短文件路径

问题描述

我有一个应用程序应该向用户显示文件的路径。假设用户输入/home/me/foo/,应用程序应该将其缩短为~/foo.

有没有办法在 Python 中做到这一点,以便它与 Linux 和 Windows 跨平台工作?

标签: pythoncross-platformfilepathpath-separator

解决方案


现在确定您要做什么,但将其更改为其他格式很简单:

newpath = "~"+filepath[9:]

如果您希望它与其他用户名一起使用,

newpath = "~/"+filepath[findfirstindex('foo'):]

推荐阅读