gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
使用python写一个脚本,将目录结构生成到json,windows环境
- User
使用python写一个脚本,将目录结构生成到json,windows环境
- Assistant
以下是一个示例脚本,它将输入目录下的所有文件和文件夹生成到JSON格式中,并在Windows环境中运行:
pythonimport os import json rootdir = "C:/Users/" # 指定目录 result = {} # 存储生成的JSON结果 for subdir, dirs, files in os.walk(rootdir): # 遍历目录 folder_name = os.path.basename(subdir) folder_contents = [] for file in files: file_path = os.path.join(subdir, file) # 获取文件路径 folder_contents.append(file_path) for dir in dirs: dir_path = os.path.join(subdir, dir) # 获取目录路径 folder_contents.append(dir_path) result[folder_name] = folder_contents # 将目录和生成的文件/文件夹列表存储到JSON中 with open("file_structure.json", "w") as json_file: # 将JSON写入文件 json.dump(result, json_file, indent=4) print("File structure saved to file_structure.json")