import os
import logging

logger = logging.getLogger("")


# 创建一个绝对路径的文件夹
def create_folder(url):
    if not os.path.exists(url):
        os.makedirs(url)


# 获取一个文件夹下的文件列表
def get_file_list(path):
    file_list = []
    for _, _, files in os.walk(path):
        file_list.extend(files)
    return file_list


# 保存文件
def save_file(file_path, file):

    try:
        destination = open(file_path, 'wb+')
        if file.multiple_chunks() is False:
            destination.write(file.read())
        else:
            for chunk in file.chunks():
                destination.write(chunk)
        destination.close()
    except Exception as e:
        logger.debug(e)
        return False
    return True


# 聚合多个文件为一个
def aggregation_files(file_url, file_name, index):
    try:
        with open(os.path.join(file_url, file_name), "ab+") as f:
            destination = open(
                os.path.join(file_url,
                             str(index) + '-' + file_name + ".bak"), "rb")
            f.write(destination.read())
    except Exception as e:
        logger.debug(e)
        print(e)
        return False
    return True
