[英]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]. 我可以从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) . 另一方面,假设您想区分以斜杠\\反斜杠开头的绝对路径或相对路径,则可以使用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: Doc说,它会检查路径是否以Unix上的斜线开头,并在切掉一个可能的驱动器号后在Win上以反斜线开头:
>>> 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) . 适用于上述所有情况的解决方案,对带有斜线或没有斜线的相对路径不敏感,将使用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
Did you try 你试过了吗
os.path.basename
or 要么
os.path.dirname
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.