Python 中没有内置的 cd
命令,因为 cd
是用于在命令行中更改当前工作目录的 shell 内置命令。但是,如果你想在 Python 脚本或程序中更改工作目录,你可以使用 os
模块中的 os.chdir()
函数。以下是一些关于如何在 Python 中使用 os.chdir()
的技巧:
- 使用绝对路径和相对路径:
- 绝对路径:从文件系统的根目录开始指定完整的路径。
- 相对路径:相对于当前工作目录指定路径。
import os # 使用绝对路径更改工作目录 os.chdir('/path/to/directory') # 使用相对路径更改工作目录 os.chdir('directory/subdirectory')
- 使用
os.getcwd()
查看当前工作目录: 在更改工作目录之前和之后,可以使用os.getcwd()
函数查看当前工作目录。
import os print("Before changing directory:", os.getcwd()) os.chdir('/path/to/directory') print("After changing directory:", os.getcwd())
- 使用
os.listdir()
列出目录内容: 在更改工作目录后,可以使用os.listdir()
函数获取目录中的文件和子目录列表。
import os os.chdir('/path/to/directory') print("Files and directories in the current directory:") for item in os.listdir(): print(item)
- 使用
os.makedirs()
创建目录: 如果需要创建一个新的目录,可以使用os.makedirs()
函数。
import os new_directory = 'directory/subdirectory' os.makedirs(new_directory, exist_ok=True) # exist_ok=True 表示如果目录已存在,不会引发错误 os.chdir(new_directory)
- 使用
os.rmdir()
删除目录: 如果需要删除一个空目录,可以使用os.rmdir()
函数。
import os directory_to_delete = 'directory/subdirectory' os.rmdir(directory_to_delete) # 请确保目录为空,否则会引发错误 os.chdir('..') # 返回上一级目录
请注意,os.chdir()
只会更改当前 Python 进程的工作目录,而不会影响其他程序或 shell 会话。