Python os.chdir()
Python中的os.chdir()方法用于将当前工作目录更改为指定路径。它只接受一个参数作为新目录路径。
语法:
os.chdir(path)
参数:
path:待修改目录的完整路径。
返回:不返回任何值
示例1
使用chdir()更改目录
# Python3 program to change the
# directory of file using os.chdir() method
# import os library
import os
# change the current directory
# to specified directory
os.chdir(r"C:\Users\Gfg\Desktop\geeks")
print("Directory changed")
输出:
Directory changed
示例2
使用os.getcwd()
要知道文件的当前工作目录,可以使用getcwd()方法。更改路径后,可以使用此方法验证当前工作目录的路径。
# import os module
import os
# change the current working directory
# to specified path
os.chdir('c:\\gfg_dir')
# verify the path using getcwd()
cwd = os.getcwd()
# print the current directory
print("Current working directory is:", cwd)
输出:
Current working directory is: c:\\gfg_dir
示例3
在更改目录时处理错误
# importing all necessary libraries
import sys, os
# initial directory
cwd = os.getcwd()
# some non existing directory
fd = 'false_dir / temp'
# trying to insert to false directory
try:
os.chdir(fd)
print("Inserting inside-", os.getcwd())
# Caching the exception
except:
print("Something wrong with specified\
directory. Exception- ", sys.exc_info())
# handling with finally
finally:
print("Restoring the path")
os.chdir(cwd)
print("Current directory is-", os.getcwd())
输出:
Inserting inside- c:\gfg_dir\gfg
Something wrong with specified directory. Exception-
Restoring the path
Current directory is- c:\gfg_dir\gfg