获得完整的争论路径

时间:2016-12-02 07:41:13

标签: python file directory

如何编写接受文件作为参数的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给出的文件的绝对路径。

如何制作上述剧本?

1 个答案:

答案 0 :(得分:3)

好的,我找到了答案:

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)
相关问题