如何在Python中获取和更改当前工作目录

时间:2020-03-05 15:31:27  来源:igfitidea点击:

在Python中处理目录中的文件时,始终最好使用绝对路径。
但是,如果我们使用的是相对路径,则需要了解当前工作目录的概念以及如何查找或者更改当前工作目录。
绝对路径指定从根目录开始的文件或者目录位置,而相对路径从当前工作目录开始。

运行Python脚本时,当前工作目录将设置为执行脚本的目录。

os python模块提供了一种与操作系统交互的可移植方式。
该模块是标准Python库的一部分,并包括用于查找和更改当前工作目录的方法。

在Python中获取当前的工作目录

Python中os模块的'getcwd()'方法返回一个字符串,其中包含当前工作目录的绝对路径。
返回的字符串不包含斜杠字符。

os.getcwd()

要使用os模块方法,必须在文件顶部导入模块。

下面是显示如何打印当前工作目录的示例:

# Import the os module
import os
# Get the current working directory
cwd = os.getcwd()
# Print the current working directory
print("Current working directory: {0}".format(cwd))
# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

输出将如下所示:

Current working directory: /home/theitroad/Desktop
os.getcwd() returns an object of type: <class 'str'>

如果要查找脚本所在的目录,请使用'os.path.realpath(__ file__)'。
它将返回一个字符串,其中包含正在运行的脚本的绝对路径。

在Python中更改当前工作目录

要在Python中更改当前的工作目录,请使用'chdir()'方法。

os.getcwd(path)

该方法接受一个参数,即我们要更改到的目录的路径。
'path'参数可以是绝对的也可以是相对的。

这是一个例子:

# Import the os module
import os
# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))
# Change the current working directory
os.chdir('/tmp')
# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))

输出将如下所示:

Current working directory: /home/theitroad/Desktop
Current working directory: /tmp

提供给“ chdir()”方法的参数必须是目录,否则会引发“ NotADirectoryError”异常。
如果指定的目录不存在,则会引发“ FileNotFoundError”异常。
如果运行脚本的用户没有必要的权限,则会引发“ PermissionError”异常。

# Import the os module
import os
path = '/var/www'
try:
    os.chdir(path)
    print("Current working directory: {0}".format(os.getcwd()))
except FileNotFoundError:
    print("Directory: {0} does not exist".format(path))
except NotADirectoryError:
    print("{0} is not a directory".format(path))
except PermissionError:
    print("You do not have permissions to change to {0}".format(path))