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

嚯嚯 发表于2020-10-23 14:29
浏览次数:
在手机上阅读
此文章约为970字,阅读需要3 分钟

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

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

在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/ywnz/Desktop

os.getcwd() returns an object of type:

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

os.path.realpath(__file__)

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

在Python中更改当前工作目录

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

os.chdir(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/ywnz/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))

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

265 个用户觉得很有用

uc电脑园提供的技术方案或与您产品的实际情况有所差异,您需在完整阅读方案并知晓其提示风险的情况下谨慎操作,避免造成任何损失。

如此好文,分享给朋友

图片来源:网络

发表评论
验证码:
评论列表
共0条