2

I would like to read a file path from command line arguments, using argparse. Is there any optimal way to check if the path is relative (file is in current directory) or the complete path is given? (Other than checking the input and adding current directory to file name if the path does not exist.)

2
  • 2
    You could use os.path.isabs. Commented May 20, 2016 at 13:36
  • 1
    This will work for me, Thanks @DisplayName Commented May 20, 2016 at 14:21

1 Answer 1

2

As Display Name said, os.path.isabs along with sys.argv is probably the best:

import sys
import os

fpath = sys.argv[-1]

print(os.path.isabs(fpath))
print(fpath)

output

>>> 
True
C:\Users\310176421\Desktop\Python\print.py
>>>

some cmd stuff

C:\Users\310176421\Desktop\Python>python print.py C:\Users\310176421\Desktop\tes
t.txt
True
C:\Users\310176421\Desktop\test.txt

C:\Users\310176421\Desktop\Python>python print.py whatever
False
whatever
Sign up to request clarification or add additional context in comments.

2 Comments

``` >>> %Run aaa.py C:\Users\motamed\Desktop\mo3ta\summary False C:UsersmotamedDesktopmo3tasummary ```
What OS and python version are you using?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.