2010-07-10 201 views
45

符號鏈接或軟鏈接的目標文件的完整(絕對路徑)當我給 ls -l命令/etc/fonts/conf.d/70-yes-bitmaps.conf如何找到蟒蛇

lrwxrwxrwx <snip> /etc/fonts/conf.d/70-yes-bitmaps.conf -> ../conf.avail/70-yes-bitmaps.conf 

所以在Python符號鏈接或軟鏈接,如何找到目標文件的完整(絕對路徑),

如果我使用

os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf')

它輸出

../conf.avail/70-yes-bitmaps.conf

,但我需要的絕對路徑而不是相對路徑,所以我期望的輸出必須是

/etc/fonts/conf.avail/70-yes-bitmaps.conf

如何與父目錄的實際完整路徑替換..符號鏈接或軟鏈接文件。

回答

8

http://docs.python.org/library/os.path.html#os.path.abspath

也joinpath和normpath,這取決於您是否是在當前工作目錄,或你的東西在其他地方工作。 normpath可能對你更直接。

更新:

明確:

os.path.normpath( 
    os.path.join( 
    os.path.dirname('/etc/fonts/conf.d/70-yes-bitmaps.conf'), 
    os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf') 
) 
) 
+2

雖然被警告:你應該通過這不是一個符號鏈接的readlink它會生氣,給下面的異常路徑: 'OSERROR:[錯誤22 ]參數無效:「你-path'' – Diego 2015-01-23 10:33:08

76
os.path.realpath(path) 

os.path.realpath返回指定的文件名的規範路徑,消除在通路中遇到的任何符號鏈接。

+1

os.path中。realpath不會消除Windows 7下Python 3.2中的符號鏈接。(一個bug?) – 2012-03-09 14:05:23

+1

嗯......我發現這已經是一個1.5年的開放bug: http://bugs.python.org/issue9949 – 2012-03-09 14:23:44

+1

是的,在3年後得到同樣的問題:c – Coburn 2015-08-22 04:16:08

12

由於unutbu說,os.path.realpath(路徑)應該是正確的答案,返回指定的文件名的規範路徑,解決任何符號鏈接到他們的目標。但它在Windows下被破壞了。

我創建的Python 3.2的補丁修復這個bug,並將其上傳到:

http://bugs.python.org/issue9949

它修復ntpath.py

我在Python32 \ LIB \真實路徑的功能「以前也把它放在我的服務器上,在這裏:

http://www.burtonsys.com/ntpath_fix_issue9949.zip

不幸的是,這個錯誤存在於PY馬拉松2.X,也和我知道,沒有修復它那裏。

0

documentation說,使用os.path.join()

The result may be either an absolute or relative pathname; if it is relative, it may be converted to an absolute pathname using os.path.join(os.path.dirname(path), result) .