2016-12-02 143 views
3

如何編碼接受文件作爲參數並打印完整路徑的Python腳本?獲取參數的完整路徑

E.g.

~/.bin/python$ ls 
./  ../  fileFinder.py  test.md 
~/.bin/python$ py fileFinder.py test.md 
/Users/theonlygusti/.bin/python/test.md 
~/.bin/python$ py fileFinder.py /Users/theonlygusti/Documents/Online/theonlygusti.github.io/index.html 
/Users/theonlygusti/Documents/Online/theonlygusti.github.io/index.html 

所以,應該找相關文件,test.md,並通過絕對路徑/Users/theonlygusti/Downloads/example.txt給出的文件也絕對路徑的絕對路徑。

如何製作上面的腳本?

+0

鑑於目前可與相同的基本名稱不同的目錄多個文件,你不能這樣做。您只需遍歷每個驅動器上的每個目錄,併爲每個使用匹配的基本名稱找到的文件生成目錄路徑。 – TigerhawkT3

+4

'os.path.abspath'會做的伎倆... – mgilson

+0

@ TigerhawkT3你錯了,這是沒有意義的 – theonlygusti

回答

1

好吧,我找到了答案:

import os 

path = "" 

if os.path.exists(sys.argv[1]): 
    path = os.path.abspath(sys.argv[1]) 
else: 
    print("Cannot find " + sys.argv[1]) 
    exit() 

print(path) 
+0

'elif'似乎是多餘的,因爲'os.path.exists'可以使用相對路徑或絕對路徑。它看起來像你只是想找到一個給定的文件是否存在。 – TigerhawkT3

+0

@ TigerhawkT3哦,我不知道。謝謝,看起來我可以更新馬答案。 – theonlygusti