在Linux Python环境中获取或更改当前工作目录的方法

本文介绍在Python环境中获取或更改当前工作目录的方法,以Linux平台为例。

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

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

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

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

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

os.getcwd()

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

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

# Import the os moduleimport os# Get the current working directorycwd = os.getcwd()# Print the current working directoryprint(“Current working directory: {0}”.format(cwd))# Print the type of the returned objectprint(“os.getcwd() returns an object of type: {0}”.format(type(cwd)))

输出将如下所示:

Current working directory: /home/ywnz/Desktop

os.getcwd() returns an object of type:

如果要查找脚本所在的目录,请使用

os.path.realpath(__file__)

它将返回一个字符串,其中包含正在运行的脚本的绝对路径。

在Python中更改当前工作目录

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

os.chdir(path)

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

这是一个例子:

# Import the os moduleimport os# Print the current working directoryprint(“Current working directory: {0}”.format(os.getcwd()))# Change the current working directoryos.chdir(‘/tmp’)# Print the current working directoryprint(“Current working directory: {0}”.format(os.getcwd()))

输出将如下所示:

Current working directory: /home/ywnz/Desktop

Current working directory: /tmp

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

# Import the os moduleimport ospath = ‘/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))

结论:要在Python中找到当前的工作目录,请使用os.getcwd(),要更改当前的工作目录,请使用os.chdir(path)。

快乐不是因为得到的多而是因为计较的少!

在Linux Python环境中获取或更改当前工作目录的方法

相关文章:

你感兴趣的文章:

标签云: