Check if directory 'B' is inside directory 'A'

0

I'm developing a script that checks the last access date of each file within every tree of a chosen directory. Files with more than X days without access will be moved to another directory. As a precaution, I need to be detected if the destination directory is inside the source directory. If it is, the script will ask for a destination directory other than the source directory.

This is the part where the target directory is requested:

msg_error = '[ERRO] Diretorio invalido, tente novamente:\n'
pasta_destino = str(input('Insira o diretorio de destino\n'))
while not path.isdir(pasta_destino):
    pasta_destino = str(input(msg_error))

I've been trying to check this out for a long time and tried everything. I'm learning python just a week and something closer to the check I was able to build was this:

if path.exists(pasta_destino in pasta_origem):
     print('Escolha outro diretório que não dentro do diretório de origem.\n')

Unfortunately it does not work, it returns 'True' regardless of the paths entered.

I'm sure this is a simple check, can you help me? Many thanks.

    
asked by anonymous 20.10.2018 / 17:12

2 answers

2

Use Pathlib:

from pathlib import Path
def is_sub(root, directory):
    p = Path(root)
    return True if list(p.glob(directory)) else False

Test on Linux (ipython terminal)

mkdir ~/teste1
cd ~/teste1
mkdir dir1

is_sub('.','dir1')
True

is_sub('.','dir2')
False

is_sub('/home/sidon','Downloads')
True

WIndows test:

is_sub('/','users')
True
    
20.10.2018 / 18:39
1
def subdir(pai, filho):
    return os.path.abspath(filho).startswith(os.path.abspath(pai) + os.path.sep)

Note that this function does not check if the directories exist , only if one is contained in the other, but it would be easy to modify and add this check.

    
22.10.2018 / 03:06