python os.curdir os.pardir返回当前目录和父目录字符串的用法

os.curdir和os.pardir

os.curdir和os.pardir为python标准库os内的两个常量,值为两个字符串,两个值如下:

  • os.curdir:返回一个代表当前目录字符串名;The constant string used by the operating system to refer to the current directory. This is '.' for Windows and POSIX. Also available via os.path .
  • os.pardir:返回当前目录的父目录字符串名;The constant string used by the operating system to refer to the parent directory. This is '..' for Windows and POSIX. Also available via os.path.

os.curdir和os.pardir的值

如上英文的解释,在Windows系统和POSIX类的操作系统(Linux和Mac os x)中,os.curdir的值为“.”,os.pardir的值为“..”,与mac终端中“cd .”指令返回当前目录和“cd ..”指令返回当前目录的上一级目录(父目录)颇为类似。

>>> import os
>>> os.curdir #操作系统为mac系统
'.'
>>> os.pardir
'..'

注意:os.curdir和os.pardir二者的值该如何使用呢?


os.curdir和os.pardir结合os.path.abspath()的使用方法和实例代码

将os.curdir和os.pardir的值作为参数传递给os.path.abspath()方法,可以返回当前目录的绝对路径和父目录的绝对路径,注意,只是返回值,当前工作目录并没有改变,实例代码如下:

>>> os.path.abspath(os.curdir) #返回值为当前目录的绝对路径
'/Users/z'
>>> os.path.abspath(os.pardir) #返回值为父目录的绝对路径
'/Users'
>>> os.getcwd() #当前的工作目录并没有改变
'/Users/z'

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.