简体   繁体   English

python3 - 根据树输出创建文件夹结构

[英]python3 - Create folder structure based on tree output

Using Python I'm extracting the folder tree of Google Drive account, but I'm stuck on how I can create the folder structure locally using os.makedirs 使用Python我正在提取Google Drive帐户的文件夹树,但我仍然坚持如何使用os.makedirs在本地创建文件夹结构

The below function currently outputs the tree correctly (I use indent to inspect this). 以下函数当前正确输出树(我使用缩进来检查它)。 This is how the Google Drive account has its folder structure. 这就是Google云端硬盘帐户的文件夹结构。

def tree_folder_contents(items_array, folder_id, indent):
    for item in items_array:
        if item['parents']:
            for parent in item['parents']:
                if folder_id == parent:
                    if item['mimeType'] == 'application/vnd.google-apps.folder':
                        print('     ' * indent + item['name'] + ' (indent: ' + str(indent) + ')')
                        tree_folder_contents(items_array, item['id'], indent+1)

The tree output: 树输出:

Folder_1 (indent: 0)
Folder_2 (indent: 0)
     Folder_2_1 (indent: 1)
          Folder_2_1_1 (indent: 2)
          Folder_2_1_2 (indent: 2)
          Folder_2_1_3 (indent: 2)
          Folder_2_1_4 (indent: 2)
Folder_3 (indent: 0)
     Folder_3_1 (indent: 1)
          Folder_3_1_1 (indent: 2)
Folder_4 (indent: 0)
Folder_5 (indent: 0)

How can I integrate os.makedirs into tree_folder_contents in order to create that folder structure locally? 如何将os.makedirs集成到tree_folder_contents中以便在本地创建该文件夹结构?

I've added a new parameter folder_path and I'm creating the folders using the dest_path = folder_path + item['name'] line. 我添加了一个新参数folder_path ,我正在使用dest_path = folder_path + item['name']行创建文件夹。

This is the full code: 这是完整的代码:

def tree_folder_contents(items_array, folder_id, folder_path, indent):
    for item in items_array:
        if item['parents']:
            for parent in item['parents']:
                if folder_id == parent:
                    if item['mimeType'] == 'application/vnd.google-apps.folder':
                        dest_path = folder_path + item['name'].replace( '/', '_' ) + '/'

                        if not os.path.exists(dest_path):
                            os.makedirs(dest_path)

                        print('     ' * indent + item['name'] + ' (indent: ' + str(indent) + ')')
                        tree_folder_contents(items_array, item['id'], dest_path, indent+1)

At the first run of tree_folder_contents , folder_path is the main directory where all account folders will be created in. 在第一次运行tree_folder_contentsfolder_path是将在其中创建所有帐户文件夹的主目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM