如何在Python中从文件名中删除前缀?
我想编写一个脚本,接收目录的路径和该目录中包含的文件的路径(可能嵌套了许多目录),并返回该文件相对于外部目录的路径 例如,如果外部目录是如何在Python中从文件名中删除前缀?,python,Python,我想编写一个脚本,接收目录的路径和该目录中包含的文件的路径(可能嵌套了许多目录),并返回该文件相对于外部目录的路径 例如,如果外部目录是/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
/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一起使用是否是测试一个文件是否位于另一个文件中的正确方法?有没有办法避免我可能需要删除的前导斜杠出现这种尴尬的情况?您可以使用
os.path
模块的commonprefix
和relpath
来查找两条路径中最长的公共前缀。它总是首选使用realpath
import os
dir_path = os.path.realpath("/home/hugomg/foo")
file_path = os.path.realpath("/home/hugomg/foo/bar/baz/unicorns.py")
common_prefix = os.path.commonprefix([dir_path,file_path])
if common_prefix != dir_path:
print("file is not inside the directory")
exit(1)
print(os.path.relpath(file_path, dir_path))
输出:
bar/baz/unicorns.txt
这也让人感觉不舒服。。。lstrip将其参数视为要删除的一组字符,而不是要删除的前缀。如果
dir\u path
和file\u path
没有标准化,绝对路径名是否仍然有效?也许relpath
更合适?看起来很接近我的要求。顺便说一句,有人指出,显然commonprefix被弃用,取而代之的是commonpath函数。