📌  相关文章
📜  使用Python更改当前工作目录

📅  最后修改于: 2022-05-13 01:54:43.389000             🧑  作者: Mango

使用Python更改当前工作目录

Python中的OS 模块用于与操作系统交互。该模块属于 Python 的标准实用程序模块,因此无需在外部安装它。如果文件名和路径无效或不可访问,或其他类型正确但操作系统不接受的参数,OS 模块中的所有函数都会引发 OSError。
要更改当前工作目录(CWD) ,请使用 os.chdir() 方法。此方法将 CWD 更改为指定路径。它只需要一个参数作为新的目录路径。
注意:当前工作目录是运行Python脚本的文件夹。

示例#1:我们将首先获取脚本的当前工作目录,然后我们将对其进行更改。下面是实现。

Python3
# Python program to change the
# current working directory
 
 
import os
 
# Function to Get the current
# working directory
def current_path():
    print("Current working directory before")
    print(os.getcwd())
    print()
 
 
# Driver's code
# Printing CWD before
current_path()
 
# Changing the CWD
os.chdir('../')
 
# Printing CWD after
current_path()


Python3
# Python program to change the
# current working directory
 
 
# 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:
    print("Inserting inside-", os.getcwd())
    os.chdir(fd)
       
# Caching the exception    
except:
    print("Something wrong with specified directory. Exception- ")
    print(sys.exc_info())
             
# handling with finally          
finally:
    print()
    print("Restoring the path")
    os.chdir(cwd)
    print("Current directory is-", os.getcwd())


输出:

Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg

Current working directory after
C:\Users\Nikhil Aggarwal\Desktop

示例 #2:在更改目录时处理错误。

Python3

# Python program to change the
# current working directory
 
 
# 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:
    print("Inserting inside-", os.getcwd())
    os.chdir(fd)
       
# Caching the exception    
except:
    print("Something wrong with specified directory. Exception- ")
    print(sys.exc_info())
             
# handling with finally          
finally:
    print()
    print("Restoring the path")
    os.chdir(cwd)
    print("Current directory is-", os.getcwd())

输出: