温馨提示×

python的cd命令怎样创建目录

小樊
84
2024-12-10 22:10:03
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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() 可以创建多级目录结构,如果父目录不存在,它会自动创建它们。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python的cd命令怎样切换目录

0