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.)
1 Answer
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
2 Comments
Mahmoud Mabrok
``` >>> %Run aaa.py C:\Users\motamed\Desktop\mo3ta\summary False C:UsersmotamedDesktopmo3tasummary ```
Pax Vobiscum
What OS and python version are you using?
os.path.isabs.