4

Python 生成目录 json 信息

 1 year ago
source link: https://www.jansora.com/notebook/107608
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 生成目录 json 信息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()


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK