【发布时间】:2017-04-11 01:33:36
【问题描述】:
我想编写一个脚本,它接收一个目录的路径和一个包含在该目录中的文件的路径(可能嵌套了许多目录很深),并返回该文件相对于外部目录的路径。
例如,如果外部目录是/home/hugomg/foo,内部文件是/home/hugomg/foo/bar/baz/unicorns.txt,我希望脚本输出bar/baz/unicorns.txt。
现在我正在使用realpath 和字符串操作:
import os
dir_path = "/home/hugomg/foo"
file_path = "/home/hugomg/foo/bar/baz/unicorns.py"
dir_path = os.path.realpath(dir_path)
file_path = os.path.realpath(file_path)
if not file_path.startswith(dir_path):
print("file is not inside the directory")
exit(1)
output = file_path[len(dir_path):]
output = output.lstrip("/")
print(output)
但是有没有更强大的方法来做到这一点?我不确定我当前的解决方案是否是正确的方法。将startswith与realpath一起使用是测试一个文件是否在另一个文件中的正确方法吗?有没有办法避免我可能需要删除前导斜线的尴尬情况?
【问题讨论】:
标签: python