如何在Python Shell中檢視/更改當前目錄?


透過OS Python模組提供了一種與作業系統互動的可移植方法。該模組是預設Python庫的一部分,包含用於查詢和修改工作目錄的工具。

本文介紹了以下內容。

__file__ 函式返回當前指令碼檔案(.py)的路徑。

獲取當前工作目錄 - os.getcwd()

函式os.getcwd() 將Python當前工作目錄的絕對路徑作為字串str返回。“獲取當前工作目錄”(getcwd)是指使用print()getcwd()列印作業系統當前工作目錄的能力。

返回的字串中省略了尾隨斜槓字元。

示例

以下是如何獲取當前工作目錄的示例

# Importing the module import os # Getting the current working directory cwd = os.getcwd() # Printing the current working directory print("Th Current working directory is: {0}".format(cwd)) # Printing the type of the returned object print("os.getcwd() returns an object of type: {0}".format(type(cwd)))

輸出

以下是上述程式碼的輸出

The Current working directory is: C:\Users\Lenovo\Desktopos.getcwd() returns an object of type: ⁢class 'str'>
os.getcwd() returns an object of type: 

更改當前工作目錄:os.chdir()

使用Python中的chdir()函式更改當前工作目錄。

該方法只允許將要更改到的目錄的路徑作為引數。您可以使用絕對路徑或相對路徑引數。

示例

以下是如何更改當前工作目錄的示例

# Importing the module import os # Printing the current working directory print("The Current working directory is: {0}".format(os.getcwd())) # Changing the current working directory os.chdir('C:\Users\Lenovo\Downloads\Works') # Print the current working directory print("The Current working directory now is: {0}".format(os.getcwd()))

輸出

以下是上述程式碼的輸出

The Current working directory is: C:\Users\Lenovo\Desktop
The Current working directory now is: C:\Users\Lenovo\Downloads\Works

注意− 如果未將目錄作為chdir()方法的引數提供,則會丟擲NotADirectoryError異常。如果未找到提供的目錄,則會引發FileNotFoundError異常。如果執行指令碼的使用者沒有所需的許可權,則會引發PermissionError異常。

示例

# Import the os module import os path = 'C:\Users\Lenovo\Downloads\Works' try: os.chdir(path) print("The Current working directory is: {0}".format(os.getcwd())) except FileNotFoundError: print("Directory: {0} does not exist".format(path)) except NotADirectoryError: print("{0} is not a directory".format(path)) except PermissionError: print("No permissions to change to {0}".format(path))

輸出

以下是上述示例的輸出

The Current working directory is: C:\Users\Lenovo\Downloads\Works

更新於:2023年8月26日

39K+ 次檢視

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.