18

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?

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • Given that there can be multiple files in different directories with the same base name, you cannot do that. All you can do is go through every single directory on every drive and produce the directory path for every file found with a matching base name. – TigerhawkT3 Dec 02 '16 at 07:42
  • 5
    `os.path.abspath` would do the trick ... – mgilson Dec 02 '16 at 07:42
  • @TigerhawkT3 you are wrong, that makes no sense – theonlygusti Dec 02 '16 at 07:43
  • Well, explain more clearly what sort of input and output you expect. – TigerhawkT3 Dec 02 '16 at 07:44
  • @mgilson - That would either need to be the current directory for a base name, or whatever absolute directory was passed for an absolute path. – TigerhawkT3 Dec 02 '16 at 07:46
  • @mgilson doesn't that _only_ work for files in same dir as the python script? – theonlygusti Dec 02 '16 at 07:47
  • If you expect a script to find the absolute path for files located anywhere on any connected drive given only the base name, you will have to crawl through directories. – TigerhawkT3 Dec 02 '16 at 07:48
  • @TigerhawkT3 read the question, that's not what I want – theonlygusti Dec 02 '16 at 07:50
  • I read your question several times and don't understand what you're expecting. Maybe you could add 1) your current code, 2) sample input, 3) expected output, and 4) actual output? That might help me understand what you want. – TigerhawkT3 Dec 02 '16 at 07:52

1 Answers1

6

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)
theonlygusti
  • 11,032
  • 11
  • 64
  • 119