python如何将相对路径转换为绝对路径?

Python (654) 2023-06-11 04:36:08

一、相对路径与绝对路径

1、参数是绝对路径,返回 True

>>>os.path.isabs('.')
False

2、参数是相对路径,返回 False

>>>os.path.isabs(os.path.abspath('.'))#利用abspath将相对路径转换为绝对路径
True

二、将相对路径转换为绝对路径的简便方法:使用os.path.abspath(path) 返回 path 参数的绝对路径的字符串。

>>>os.path.abspath('.\\Scripts')
'C:\\ProgramFiles(x86)\\Scripts'

补充:从 start 路径到 path 的相对路径的字符串

>>>os.path.relpath('C:\\Windows','C:\\')
'Windows'

如果没有提供 start,使用当前工作目录作为开始路径

>>>path='C:\\ProgramFiles(x86)'

>>>os.path.basename(path)#path参数最后一个斜杠之后的所有内容
'ProgramFiles(x86)'
>>>os.path.dirname(path)#path参数最后一个斜杠之前的所有内容
'C:\\'
THE END

发表回复