在 Python 中处理目录中的文件时,使用绝对路径始终是一个好主意。但是,如果您使用相对路径,则需要了解当前工作目录的概念以及如何查找或更改当前工作目录。绝对路径指定从根目录开始的文件或目录位置,而相对路径从当前工作目录开始。
当您运行 Python 脚本时,当前工作目录将设置为执行脚本的目录。
os python 模块提供了一种与操作系统交互的可移植方式。该模块是标准 Python 库的一部分,包含查找和更改当前工作目录的方法。
在Python中获取当前工作目录#
The getcwd()
Python 中 os 模块的方法返回一个字符串,其中包含当前工作目录的绝对路径。返回的字符串不包含尾部斜杠字符。
要使用 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/linuxize/Desktop
os.getcwd() returns an object of type: <class 'str'>
如果你想找到脚本所在的目录,使用os.path.realpath(__file__)
。它将返回一个包含正在运行的脚本的绝对路径的字符串。
在 Python 中更改当前工作目录#
要更改 Python 中的当前工作目录,请使用chdir()
method.
该方法接受一个参数,即要更改到的目录的路径。这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/linuxize/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)
.
如果您有任何问题或反馈,请随时发表评论。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)