Move aquifers by extension, PYTHON

Asked

Viewed 120 times

1

Good afternoon,

I want to fine tune my skills in PY, and I’m in a small script to move files from one place to another, but I would like to do this and not be guided by the name of the file, but rather by the extension of the same, example *.pdf or *.doc, however as I am beginner in python I still do not know which function to use for this.

Follow my code (incomplete still missing logic of moving files)

# Ordernar arquivos Area de trabalho

import os

nameUser = os.getlogin() # Capturando nome do usuario
desktop_user = 'c:\\Users\\'+nameUser+'\\Desktop'
os.chdir(desktop_user) # Mudando para DESKTOP do usuario logado no momento

######### Funções #########

# Função criada para criar diretorios caso eles não existam
def criarDir():
    dirDoc = ['Documentos PDF', 'Documentos WORD','Documentos EXCEL',
              'Documentos TXT', 'Outros Arquivos', 'Multmidia']
    for dir in dirDoc:
        if not os.path.exists(dir):
            os.makedirs(dir)
        else:
            print('Diretorio {} ja existe !' .format(dir))
    return  dirDoc
def moveArquivos(listaDir):
    fileList = ['.doc','.docx', '.xlsx', '.txt', '.pdf', '.xls', '.csv',
                '.ppt', '.pps']
    fileMidia = ['.jpg', '.jpeg','.mp3', '.wav','.mid', '.mp4', '.mov']



    #for file in fileList:
     #   if

1 answer

1


You can take the file name and discover the file extension from it:

nome_do_arquivo = '/home/user/pudim.jpg'
file_splited = nome_do_arquivo.split(".")
extension_name = file_splited[-1]
print(extension_name) # OUT: 'jpg'

This code divides the file name into a list, where the . sets the end of that element and starts another one. The magic of taking the extension is in file_splited[-1], where it takes the last element from the list.

  • for file_stat in lista_arquivos_desktop: contaChar = 0 # Created to get the current position of the Indice, and thus be used to get the file extension word_temp_list = list(file_stat) # will contain the list of the current word of the current looping for char in word_temp_list:
 if char == '.':
 extensao = file_stat[contaChar:] # Obtendo a extensao do arquivo
 arquivo_bruto = file_stat
 aux_moveArquivo(extensao, arquivo_bruto)
 contaChar += 1

Browser other questions tagged

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