Python 中沒有內置的 cd
命令來更改目錄,因為 cd
是 Unix 和類 Unix 系統(如 Linux)中的 shell 內置命令。在 Python 中,你可以使用 os
模塊中的 os.chdir()
函數來更改當前工作目錄,或者使用 os.makedirs()
來創建新的目錄。
以下是使用 os.chdir()
更改當前工作目錄的示例:
import os
# 切換到指定目錄
os.chdir('/path/to/directory')
以下是使用 os.makedirs()
創建新目錄的示例:
import os
# 創建一個名為 'new_directory' 的目錄
new_directory = 'new_directory'
if not os.path.exists(new_directory):
os.makedirs(new_directory)
print(f"Directory '{new_directory}' created.")
else:
print(f"Directory '{new_directory}' already exists.")
請注意,os.makedirs()
可以創建多級目錄結構,如果父目錄不存在,它會自動創建它們。