参考:Python windows路径转Linux路径
例如笔者需要获取当前脚本 test2.py 所在的路径,并将该路径转换为Linux下的路径:
import os
import sys
if __name__ == "__main__":
print("this is test2 file ")
sh_path = os.path.dirname(os.path.abspath(sys.argv[0]))
print(sh_path)
sh_path = '/'.join(sh_path.split('\\')) # transform the windows path to linux path
print(sh_path)
运行该代码,结果如下:
$ python test2.py
this is test2 file
E:\code-study\python
E:/code-study/python
split将路径按照‘\’(‘\’表示字符‘\’,参考转义字符)分割成列表 [‘E:’, ‘code-study’, ‘python’] ,然后join用‘/’将其连接起来。
参考转义:
转义字符1
转义字符2