Python 本身沒有內置的 cd 命令,因為 cd 是 Unix 和類 Unix 系統(如 Linux)中的 shell 內置命令,用于更改當前工作目錄。然而,Python 可以通過 os 模塊來訪問和操作文件和目錄。
要使用 Python 訪問不同的路徑,你可以使用 os 模塊中的 os.chdir() 函數來更改當前工作目錄,以及 os.getcwd() 函數來獲取當前工作目錄。此外,你還可以使用 os.listdir() 函數來列出指定目錄中的文件和子目錄。
以下是一個簡單的示例:
import os
# 獲取當前工作目錄
current_directory = os.getcwd()
print(f"當前工作目錄: {current_directory}")
# 更改當前工作目錄
new_directory = "/path/to/your/desired/directory"
os.chdir(new_directory)
print(f"更改后的工作目錄: {os.getcwd()}")
# 列出指定目錄中的文件和子目錄
directory_contents = os.listdir(new_directory)
print(f"{new_directory} 中的文件和子目錄: {directory_contents}")
請注意,要使用 os.chdir() 和 os.listdir() 函數,你需要確保指定的路徑是有效的,并且 Python 進程具有訪問該路徑的權限。