获得完整的争论路径

the*_*sti 11 python directory file

如何编写接受文件作为参数的Python脚本并打印其完整路径?

例如

~/.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
Run Code Online (Sandbox Code Playgroud)

因此,它应该找到相对文件的绝对路径test.md,以及通过绝对路径给出的文件的绝对路径/Users/theonlygusti/Downloads/example.txt.

我怎样才能制作上面的剧本?

the*_*sti 6

好的,我找到了答案:

import os
import sys

relative_path = sys.argv[1]

if os.path.exists(relative_path):
    print(os.path.abspath(relative_path))
else:
    print("Cannot find " + relative_path)
    exit(1)
Run Code Online (Sandbox Code Playgroud)