Create file structure according to the tree result

I have a directory in remote machine with large files, and I want to create the file structure the same as in the remote file structure. There was a tree command, we can use tree -J command to get the file structure in json format, so I think that we can create the file structure according to the tree -J result.

Get the file structure with tree command

tree -J <root dir> > root_dir_tree.json
# copy the root_dir_tree.json to local machine

Create file structure with python

Create a file named with create_struture.py

#!/usr/bin/env python3

import json
import os
import sys

def create_structure(contents, parent_path='.'):
    for item in contents:
        # Skip the report object
        if 'name' not in item:
            continue

        name = item['name']
        path = os.path.join(parent_path, name)
        if item['type'] == 'directory':
            os.makedirs(path, exist_ok=True)
            create_structure(item['contents'], path)
        elif item['type'] == 'file':
            open(path, 'a').close()

def main(json_file_path):
    # Load the JSON structure from the file provided as an argument
    with open(json_file_path, 'r') as f:
        tree = json.load(f)
    
    # Create the directory structure
    create_structure(tree)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print("Usage: python create_structure.py <path_to_json_file>")
        sys.exit(1)

    json_file_path = sys.argv[1]
    main(json_file_path)

Use the command to create the structure

create_structure.py root_dir_tree.json
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值