Python中的OS模块提供了与操作系统进行交互的功能。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的功能的便携式方法。
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')
# varify the path using getcwd()
cwd = os.getcwd()
# print the current director