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

Asked

Viewed 78 times

0

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

This is the part where the destination 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 I’ve tried everything. I’ve only been learning python for a week and something closer to the check I was able to assemble 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, returns 'True' independent of the inserted paths.

I’m sure this is a simple check, can you help me? Thank you very much.

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

Testing on Linux (ipython terminal)

mkdir ~/teste1
cd ~/teste1
mkdir dir1

is_sub('.','dir1')
True

is_sub('.','dir2')
False

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

Test on Windows:

is_sub('/','users')
True
  • It only works if the directory is immediately inside the other, IE, can not detect the case of directory checking to be at 2 or more subdirectory levels inside the root directory root.

  • @nosklo, I focused on the question, and I didn’t realize this need, but it would be very simple to adapt to what you suggest.

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 whether directories exist, only if one is contained in the other, however, it would be easy to modify and add further this check.

  • Dude, it’s a good idea, but you have to take care of a deal, abspath returns a path without the bar at the end. If you are going to use string comparison for this you have to add this bar, otherwise your code will say that /minha/pasta_filha/teste is contained in /minha/pasta

  • @fernandosavio well thought out, I edited the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.