2017-04-11 47 views
2

我想編寫一個腳本,它接收到一個目錄的路徑和該目錄中包含的文件的路徑(可能嵌套多個目錄深度)並返回該文件相對於外部目錄的路徑。如何從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/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一起測試一個文件是否在另一個文件中是正確的方法?有沒有辦法避免那種我可能需要刪除的主要斜槓的尷尬局面?

回答

1

您可以使用os.path模塊的commonprefixrelpath來查找兩條路徑的最長公共前綴。它始終傾向於使用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 
+0

這也感到過... lstrip對待自己的參數作爲一組字符去掉,不作爲前綴刪除。如果'dir_path'和'file_path'沒有標準化,絕對路徑名是否仍然有效? – hugomg

+0

也許'relpath'更適合? – abccd

+0

看起來像[這個問題](http://stackoverflow.com/questions/7287996/python-get-relative-path-from-comparing-two-absolute-paths/7288019#7288019)接近我的要求。順便說一句,有人指出,顯然commonprefix已被棄用,以支持commonpath功能。 – hugomg

相關問題