简体   繁体   中英

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.(ie is it file or file path)

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

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

Did you try

os.path.basename 

or

os.path.dirname

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM