Check the file extension and change its directory

Asked

Viewed 346 times

0

I’m having trouble with a python script that checks if there are files with a specific extension in the directory and moves the whole directory to another destination

This is a test to automate the process of moving a directory to another place depending on its extension, but I can only accomplish this if all the files have the same extension, otherwise, even if there is only one file with the desired extension it does not perform directory change.

Directory contents 'testar_mover_directory':

text file.txt

python file.py

import os, shutil


def verificar_dir(diretorio, extensao, destino):
    if (os.path.exists(diretorio) == True):
        for pasta, subpastas, arquivos in os.walk(diretorio):
            for arquivo in arquivos:
                extensao_arquivo = arquivo.endswith(extensao)
                if (extensao_arquivo == True):
                    result = ('Existem arquivos com a extensão {} na pasta').format(extensao)
                    if (os.path.exists(destino) == True):
                        shutil.move(diretorio, destino)
                    else:
                        result = 'O diretório de destino não existe'
                else:
                    result = ('Não existem arquivos com a extensão {} na pasta').format(extensao)
        return print(result)

    else:
        print('Este diretório não existe')

diretorio = input('Qual é o diretório que você deseja verificar? ')
extensao = input('Qual é a extensão que você procura? ')
destino = input('Qual será o destino deste diretório? ')
print('')

verificar_dir(diretorio, extensao, destino)

Example: I have a 'teste_mover_directory' folder on the desktop with '.txt' and '.py' files and want to move it to the 'Projects' directory, but the script does not make the change even if there is a '.py' file inside the folder.

  • this script has some problems, but the code as it is will make the change when find the first file with the desired extension. (I don’t even know if it doesn’t break immediately after that). Definitely this above code will not do the action "only if all files have the desired extension". Either the code is different than what you run there, or the question is unclear.

1 answer

1


For versions equal to or greater than 3.4 of the language use the package pathlib to manage directories and files. Its API is more direct and simple than the one provided by the package os.

  1. To open a directory, use foo = pathlib.Path('./foo');
  2. To search for files with a certain extension, use foo.glob('*.py');
  3. If you return at least one file, rename the directory;

In code it would look something like:

from pathlib import Path

foo = Path('foo')

for _ in foo.glob('*.py'):
    foo.rename('bar')
    break
else:
    print('Nenhum arquivo .py encontrado')

So if you own the directory:

/foo
    main.py

When running the program you will have

/bar
    main.py

But beware of running conditions if there are multiple processes manipulating the same directory in parallel.

  • Thank you very much! I didn’t know this API, I will search more about it and its functionalities. The code is much more friendly and simple

Browser other questions tagged

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