Python是一种面向对象编程语言,它包含了一组完善而且容易理解的标准库,能够轻松完成很多常见的任务。有时工作中,需要更改工作目录,下面就来看下Python如何更改当前工作目录。
我们可以使用chdir()方法,在Python中更改当前的工作目录。
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/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))
相关推荐:
(本文由美国主机侦探原创,转载请注明出处“美国主机侦探”和原文地址!)

微信扫码加好友进群
主机优惠码及时掌握

QQ群号:938255063
主机优惠发布与交流