os模块提供了许多与操作系统交互的函数,包括操作目录的函数。
1、导入os模块:
import os2、获取当前工作目录:使用os模块的getcwd()方法获取当前工作目录。
current_dir = os.getcwd()print(current_dir)3、改变当前工作目录:使用os模块的chdir()方法改变当前工作目录
new_dir = '/path/to/new/directory'os.chdir(new_dir)4、列出目录下的文件和子目录:使用os模块的listdir()方法列出目录下的所有文件和子目录
files = os.listdir('.')print(files)5、创建目录:使用os模块的mkdir()方法创建一个新目录。
new_dir = 'new_directory'os.mkdir(new_dir)6、删除目录:使用os模块的rmdir()方法删除一个空目录
dir_to_delete = 'new_directory'os.rmdir(dir_to_delete)7、重命名目录:使用os模块的rename()方法重命名一个目录。
old_name = 'old_directory'new_name = 'new_directory'os.rename(old_name, new_name)8、检查目录是否存在:使用os模块的path.exists()方法检查一个目录是否存在。
dir_path = '/path/to/directory'if os.path.exists(dir_path):print('Directory exists')else:print('Directory does not exist')