0

os.path.isdir() is returning false even when i'm passing a directory path to the function. i'm anexing the code snippet. the code creates a folder called "arquivos" , to test, just create some files / folders inside.

import os
class Arquivos():
    working_path = None
    arquivos = dict() 
    def __init__(self, pasta = "arquivos" ):
        directory = os.path.dirname(os.path.abspath(__file__)) 
        directory = os.path.join(directory,pasta) 
        try:
            if not os.path.exists(directory):
                os.makedirs(directory)
        except Exception as e:
            print(e)
        self.working_path = directory
    def atualiza_arquivos(self):
        """Cria uma lista com os arquivos e pastas do diretório
            de trabalho"""
        _lista = os.listdir(self.working_path)
        result = dict()
        for arq in _lista:
            """ bug ,era pra retornar True só quando
                fossem pastas. """ 
            caminho = os.path.join(self.working_path, arq)
            result['pasta'] = os.path.isdir(caminho)
            infos = os.stat(caminho)
            result['ultima_mod'] = infos[8]
            result['tam'] = infos[6]  
            self.arquivos[arq] = result 
if __name__ == "__main__":
    obj = Arquivos()
    obj.atualiza_arquivos()
    print(obj.arquivos)
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
WagnerAlbJr
  • 190
  • 1
  • 12

1 Answers1

0

Your obj.arquivos will have copies of the same dictionary (containing data for the last file / dir iterated).
That is because result dict is created outside the loop (for arq in _lista:) and for each item iterated, you're just overwriting result values and add a reference to it in self.arquivos.
To correct your problem, create a result instance for each iterated item, by moving it into the loop.

Partial snippet:

        # Rest of the code
        _lista = os.listdir(self.working_path)
        for arq in _lista:
            result = dict()
            # Rest of the code
CristiFati
  • 38,250
  • 9
  • 50
  • 87