Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get full path of argument [duplicate]

How can I code a Python script that accepts a file as an argument and prints its full path?

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

So, it should find the absolute path of relative files, test.md, and also absolute path of files given via an absolute path /Users/theonlygusti/Downloads/example.txt.

How can I make a script like above?

like image 429
theonlygusti Avatar asked Dec 02 '16 07:12

theonlygusti


People also ask

How do you get the full path in shell?

In this case, first, we need the current script's path, and from it, we use dirname to get the directory path of the script file. Once we have that, we cd into the folder and print the working directory. To get the full or absolute path, we attach the basename of the script file to the directory path or $DIR_PATH.

How do I show the full path in Linux?

To obtain the full path of a file, we use the readlink command. readlink prints the absolute path of a symbolic link, but as a side-effect, it also prints the absolute path for a relative path. In the case of the first command, readlink resolves the relative path of foo/ to the absolute path of /home/example/foo/.

What does __ file __ mean in Python?

__file__ (A Special variable) in Python A double underscore variable in Python is usually referred to as a dunder. A dunder variable is a variable that Python has defined so that it can use it in a “Special way”. This Special way depends on the variable that is being used.

How do I find the absolute path of a directory?

To find the full absolute path of the current directory, use the pwd command. Once you've determined the path to the current directory, the absolute path to the file is the path plus the name of the file.


1 Answers

Ok, I found an answer:

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)
like image 101
theonlygusti Avatar answered Sep 24 '22 09:09

theonlygusti