Python 生成目录 json 信息

Python 生成目录 json 信息

import os
import argparse
import json
import time

def generate_directory_tree(start_path):
    dir_tree = []
    for item in os.listdir(start_path):
        item_path = os.path.join(start_path, item)
        item_info = {
            'name': item,
            'updated_at': time.ctime(os.path.getctime(item_path)),
        }
        if os.path.isdir(item_path):
            item_info['children'] = generate_directory_tree(item_path)
        else:
            item_info['children'] = None
        dir_tree.append(item_info)
    return dir_tree

def main():
    parser = argparse.ArgumentParser(description='Generate a directory tree as a JSON file.')
    parser.add_argument('input_directory', help='Path to the input directory')
    parser.add_argument('output_file', help='Path to the output JSON file')

    args = parser.parse_args()

    directory_tree = generate_directory_tree(args.input_directory)

    with open(args.output_file, 'w') as f:
        json.dump(directory_tree, f, indent=4)

if __name__ == '__main__':
    main()

评论栏