1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- import os
- import shutil
- class DirectoryUtil:
- @staticmethod
- def create_directory(path):
- """
- 创建一个新目录。如果目录已存在,则不执行任何操作。
- :param path: 要创建的目录路径
- """
- try:
- os.makedirs(path, exist_ok=True)
- print(f"Directory '{path}' created successfully.")
- except OSError as error:
- print(f"Creating directory '{path}' failed. Error: {error}")
- @staticmethod
- def delete_directory(path):
- """
- 删除一个目录及其所有内容。
- :param path: 要删除的目录路径
- """
- try:
- shutil.rmtree(path)
- print(f"Directory '{path}' deleted successfully.")
- except OSError as error:
- print(f"Deleting directory '{path}' failed. Error: {error}")
- @staticmethod
- def list_directory_contents(path):
- """
- 列出目录中的所有文件和子目录。
- :param path: 目录路径
- :return: 目录内容的列表
- """
- try:
- contents = os.listdir(path)
- print(f"Contents of directory '{path}': {contents}")
- return contents
- except OSError as error:
- print(f"Listing contents of directory '{path}' failed. Error: {error}")
- return []
-
- @staticmethod
- def list_directory(path):
- """
- 列出目录中的所有文件和子目录。
- :param path: 目录路径
- :return: 指定目录、子目录列表、文件列表
- """
- try:
- return os.walk(path)
- except OSError as error:
- print(f"Listing contents of directory '{path}' failed. Error: {error}")
- return path,None,None
- @staticmethod
- def check_directory_exists(path):
- """
- 检查一个目录是否存在。
- :param path: 目录路径
- :return: 如果目录存在则返回True,否则返回False
- """
- return os.path.exists(path) and os.path.isdir(path)
- # 使用示例
- if __name__ == "__main__":
- path = 'E:\\BaiduNetdiskDownload\\merge1' # 替换为你的目录路径
- # 创建目录
- DirectoryUtil.create_directory(path)
- # 检查目录是否存在
- if DirectoryUtil.check_directory_exists(path):
- print(f"Directory '{path}' exists.")
- # 列出目录内容
- DirectoryUtil.list_directory_contents(path)
- results=DirectoryUtil.list_directory(path)
- for root,dirs,files in results:
- print(root)
- print(dirs)
- print(files)
- # 删除目录
- # 注意:这将删除目录及其所有内容,请谨慎操作!
- # DirectoryTool.delete_directory(path)
|