获取参数的完整路径

18

我该如何编写一个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

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

我该如何创建像上面那样的脚本?


5
os.path.abspath 可以解决问题... - mgilson
@TigerhawkT3,你错了,那没有任何意义。 - theonlygusti
请更清楚地解释您期望的输入和输出类型。 - TigerhawkT3
@mgilson - 这要么是当前目录作为基本名称,要么是传递的绝对路径所在的绝对目录。 - TigerhawkT3
@mgilson 这只适用于与 Python 脚本在同一目录中的文件,对吧? - theonlygusti
显示剩余4条评论
1个回答

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接