根据文件路径创建多个文件夹

时间:2017-06-09 19:53:04

标签: python

我有一个庞大的目录列表,我正在尝试将指定的目录/文件夹从一个地方复制到另一个地方,并尝试复制'层次结构'但是却没有做到这一点。

list_of_dirs = [
'/serverA/user_data/2017_Jan/2017_01_25/reference/images/setA/',
'/serverA/user_data/2017_Jan/2017_01_26/reference/images/setA/',
 ]

lib_path = '/serverB/user_data'
dirs_length = len(list_of_dirs)

collate_date_names = []   

def create_main_folder(main_folder_name):
    base_folder_path = '{0}/{1}/'.format(lib_path, main_folder_name)
    base_folder = os.path.dirname(base_folder_path)
    if not os.path.exists(base_folder):
        os.makedirs(base_folder_path)



def create_sub_date_folder(base_folder, folder_name):
    folder_path = '{0}/{1}/{2}/'.format(lib_path, base_folder, folder_name)
    base_folder = os.path.dirname(folder_path)
    if not os.path.exists(base_folder):
        os.makedirs(folder_path)

def main():
    for directory in enumerate(list_of_dirs):
        date_range_string = directory[1].split('/')[3]
        create_main_folder(date_range_string)

        if date_range_string in directory[1]:
            folder_name = directory[1].split('/')[-2]
            create_sub_date_folder(date_range_string, folder_name)

            new_main_folder = '{0}/{1}'.format(lib_path, date_range_string)
            new_folder_path = '{0}/{1}/{2}'.format(lib_path, date_range_string, folder_name)

            subprocess.call('cp -r {0} {1}'.format(directory[1], new_main_folder), shell=True)

main()

我尝试创建这些多个文件夹的方式似乎并不理想,因为我只是在使用split命令时尝试获取下一个项目。

在运行上面的代码时,这是我看到的层次结构,而不是我想要的:

|- 2017_Jan
|--|-- 2017_01_25
|--|--|-- setA
|--|-- 2017_01_26
|--|--|-- setA

而这正是我想要实现的目标:

|- 2017_Jan
|--|-- 2017_01_25
|--|--|-- reference
|--|--|--|-- images
|--|--|--|--|-- setA
|--|-- 2017_01_26
|--|--|-- reference
|--|--|--|-- images
|--|--|--|--|-- setA

创建这种结构的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

除非我从你的解释中得不到什么,否则这看起来比它需要的更复杂。您所需要的只是削减公共前缀路径并创建其余路径,大概在另一条路径上:

import os

list_of_dirs = [
    '/serverA/user_data/2017_Jan/2017_01_25/reference/images/setA/',
    '/serverA/user_data/2017_Jan/2017_01_26/reference/images/setA/',
]

source_path = "/serverA/user_data/"  # strip off this from all paths
target_path = "/serverB/user_data/"  # destination for the paths

for path in list_of_dirs:
    if path.startswith(source_path):  # just in case we have a path without a common prefix
        path = path[len(source_path):]
    os.makedirs(target_path + path, exist_ok=True)  # this creates the desired path

# gives:
#
# / serverB
#    |-- user_data
#       |-- 2017_Jan
#          |-- 2017_01_25
#          |  |-- reference
#          |      |-- images
#          |         |-- setA
#          |-- 2017_01_26
#             |-- reference
#                |-- images
#                   |-- setA