Python os.chdir() 方法



Python os.chdir() 方法將當前工作目錄更改為給定的路徑。此命令有時用作某些系統上 cd shell 命令的別名。

執行所有命令的目錄稱為當前工作目錄。它可以是資料庫檔案、資料夾、庫或目錄。當前工作目錄也稱為當前工作目錄或僅工作目錄。此方法不返回值。

語法

以下是Python os.chdir() 方法的語法:

os.chdir(path)

引數

  • path - 這是要更改為新位置的目錄的完整路徑。

返回值

此方法不返回值。

示例 1

以下示例顯示了 Python os.chdir() 方法的用法。這裡我們將當前工作目錄更改為給定的路徑“/usr/tmp”。

import os
path = "/usr/tmp"
# change the directory
x = os.chdir(path)
print ("Directory changed successfully",x)

當我們執行上面的程式時,它會產生以下結果:

Directory changed successfully /usr/tmp

示例 2

在這裡,我們使用 getcwd() 方法 來了解檔案的當前工作目錄。更改檔案路徑後,我們使用 os.chdir() 方法驗證當前工作目錄的路徑。

# importing the module
import os
# changing the current working directory to the given path
os.chdir('D:\Sarika Work')
# verifying the path using getcwd()
current = os.getcwd()
# printing the current working directory
print("The current working directory is:", current)

執行上述程式碼時,我們得到以下輸出:

The current working directory is: D:\Sarika Work

示例 3

如果請求的目錄不存在,則此方法會引發 FileNotFoundError。

# importing the modules
import sys
import os
# the current directory
cd = os.getcwd()
# some false directory
nd = 'nonexist_dir / temp'
# trying to insert to the non existing directory
try:
   os.chdir(nd)
   print("Changing the path to:", os.getcwd())
# Caching the exception
except:
   print("Something went wrong with the given directory", sys.exc_info())
# handling with finally		
finally:
   print("Restore the path")
   os.chdir(cd)
   print("The current working directory is:", os.getcwd())

以下是上述程式碼的輸出:

Something went wrong with the given directory (<class 'FileNotFoundError'>, FileNotFoundError(2, 'The system cannot find the path specified'), <traceback object at 0x00000152D60B5640>)
Restore the path
The current working directory is: C:\Users\Lenovo\Desktop

示例 4

現在,我們將當前工作目錄更改為主目錄。

import os
print("The current working directory is:", os.getcwd())
# Changing the working directory to home directory
x = os.chdir(os.path.expanduser('~'))
print("The Current directory now is:",os.getcwd())

上述程式碼的輸出如下:

The current working directory is: C:\Users\Lenovo\Desktop
The Current directory now is: C:\Users\Lenovo
os_file_methods.htm
廣告