获取参数的完整路径
问题描述:
如何编码接受文件作为参数并打印完整路径的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
给出的文件也绝对路径的绝对路径。
如何制作上面的脚本?
答
好吧,我找到了答案:
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
鉴于目前可与相同的基本名称不同的目录多个文件,你不能这样做。您只需遍历每个驱动器上的每个目录,并为每个使用匹配的基本名称找到的文件生成目录路径。 – TigerhawkT3
'os.path.abspath'会做的伎俩... – mgilson
@ TigerhawkT3你错了,这是没有意义的 – theonlygusti