Python os.getcwd()
Python os模块中的所有函数在文件名和路径无效或不可访问,或其他具有正确类型但操作系统不接受的参数时都会引发OSError。
Python os.getcwd()方法告诉我们当前工作目录(CWD)的位置。
语法:os.getcwd()
参数:不需要参数。
返回值:该方法返回一个表示当前工作目录的字符串。
示例1
使用os.getcwd()方法获取当前工作目录
# Python program to explain os.getcwd() method
# importing os module
import os
# Get the current working
# directory (CWD)
cwd = os.getcwd()
# Print the current working
# directory (CWD)
print("Current working directory:", cwd)
输出:
Current working directory: C:\Users\Rajnish\AppData\Local\Programs\Python\Python37
示例2
使用os.getcwd()方法获取GeeksforGeeks的当前工作目录,该目录是根目录
# Python program to explain os.getcwd() method
# importing os module
import os
# Get the current working
# directory (CWD)
cwd = os.getcwd()
# Print the current working
# directory (CWD)
# which is root in this case
print("Current working directory:", cwd)
输出:
Current working directory: /