utils.py 1.22 KB
import os
from requests import get

def isformat(file, typenames):
    if type(file) != str:
        return False
        
    if type(typenames) == str:
        typenames = [typenames]

    dot = file.rfind('.')

    if dot < 0:
        for t in typenames:
            if file == t:
                return True
        return False
    
    ext = file[dot + 1 :]

    for t in typenames:
        if ext == t:
            return True

    return False

def downloadFiles(root, dir, urls):
    if not os.path.exists(root):
        os.mkdir(root)

    path = os.path.join(root, dir)

    if not os.path.exists(path):
        os.mkdir(path)
    else:
        return

    for url in urls:
        name = os.path.basename(url)
        with open(os.path.join(path, name), 'wb') as f:
            try:
                response = get(url)
                f.write(response.content)

            except Exception as e:
                print(e)
                f.close()
                break

            f.close()

def removeEmptyDirectories(root):
    cnt = 0
    for dir in os.listdir(root):
        d = os.path.join(root, dir)
        if len(os.listdir(d)) == 0: #empty
            os.rmdir(d)
            cnt += 1

    print(cnt, "empty directories removed")