user765443
user765443

Reputation:

differentiate between file name and file path

I need to invoke different functionality if we pass file name and file path

ex

python test.py  test1 (invoke different function)         
python test.py  /home/sai/test1 (invoke different function)

I can get the argument from sys.argv[1]. But I am not able to differentiate into file and filepath.(i.e is it file or file path)

Upvotes: 1

Views: 1370

Answers (3)

Pshemy108
Pshemy108

Reputation: 323

It's a tricky bit as a name of the file is also a valid relative path, right? You can not differentiate it.

On the other hand assuming you would like to differentiate an absolute path or a relative path starting with a slash\backslash you could use os.path.isabs(path). Doc says it checks if the path starts with slash on Unix, backlash on Win after chopping a potential drive letter:

>>> import os
>>> os.path.isabs('C:\\folder\\name.txt')
True
>>> os.path.isabs('\\folder\\name.txt')
True
>>> os.path.isabs('name.txt')
False

However this will fail with a relative path not beginint with slash:

>>> os.path.isabs('folder\\name.txt')
False

The solution that would work with all cases mentioned above, not sensitive to relative paths with slashes or without them, would be to perform a comparison of the tail of path with the path itself using os.path.basename(path). If they are equal it's just a name:

>>> os.path.basename('C:\\folder\\name.txt') == 'C:\\folder\\name.txt'
False
>>> os.path.basename('\\folder\\name.txt') == '\\folder\\name.txt'
False
>>> os.path.basename('folder\\name.txt') == 'folder\\name.txt'
False
>>> os.path.basename('name.txt') == 'name.txt'
True

Upvotes: 1

srhegde
srhegde

Reputation: 593

Did you try

os.path.basename 

or

os.path.dirname

Upvotes: 0

Alex L
Alex L

Reputation: 8925

You can use isdir() and isfile():

File:

>>> os.path.isdir('a.txt')
False
>>> os.path.isfile('a.txt')
True

Dir:

>>> os.path.isfile('Doc')
False
>>> os.path.isdir('Doc')
True

Upvotes: 0

Related Questions