Python操作系统。chdir()方法

操作系统模块 在Python中,提供了与操作系统交互的函数。OS属于Python的标准实用程序模块。该模块提供了一种使用操作系统相关功能的便携方式。 操作系统。chdir() 方法,用于将当前工作目录更改为指定路径。它只接受一个参数作为新的目录路径。

null

语法: 操作系统。chdir(路径) 参数: 路径: 要更改为新目录路径的目录的完整路径。 返回: 不返回任何值

代码#1: 使用chdir()更改目录

Python3

# 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:UsersGfgDesktopgeeks" )
print ( "Directory changed" )


输出:

Directory changed

代码#2: 操作系统的使用。getcwd() 要知道文件的当前工作目录,可以使用getcwd()方法。更改路径后,可以使用此方法验证当前工作目录的路径。

Python3

# 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: 更改目录时处理错误

Python3

# 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_dirgfgSomething wrong with specified directory. Exception- Restoring the pathCurrent directory is- c:gfg_dirgfg
© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享