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?
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.
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/.
__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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With