Skip to main content
 首页 » 编程设计

python之如何从 Python 中的文件名中删除前缀

2025年02月15日9lovecherry

<分区>

我想编写一个脚本来接收目录路径和该目录中包含的文件路径(可能嵌套了很多目录)并返回该文件相对于外部目录的路径。

例如,如果外部目录是/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 一起使用是测试一个文件在另一个文件中的正确方法吗?有没有办法避免我可能需要删除的前导斜线的尴尬情况?