命令行工具的路径都是根据pwd路径的相对路径,当然也可以输入绝对路径,当相对路径会增加易用性。python的os.path模块有几个函数可以直接处理相对路径,在编写自己的命令行工具时,使用这写函数可以轻松处理相对路径的问题。
本文介绍os.path.abspath和os.path.exists,前者将相对路径直接转换成绝对路径,后者判断一个相对路径是否存在。请看下面示例:
>>> import os
>>>
>>> os.getcwd()
'/home/xinlin'
>>> os.path.abspath('')
'/home/xinlin'
>>> os.path.abspath('.')
'/home/xinlin'
>>> os.path.abspath('..')
'/home'
>>> os.path.abspath('repos/smally/README.md')
'/home/xinlin/repos/smally/README.md'
>>> os.path.abspath('repos/smally/../smally/../keepy/../smally/README.md')
'/home/xinlin/repos/smally/README.md'
>>>
>>> os.path.exists('') # can not be empty
False
>>> os.path.exists('.')
True
>>> os.path.exists('..')
True
>>> os.path.exists('repos/smally/README.md')
True
>>> os.path.exists('repos/smally/../smally/../keepy/../smally/README.md')
True
这两个函数在接收命令行输入的相对路径时,使用很顺手。os.path模块的其它函数也可以处理相对路径,请自行测试。
-- EOF --