0

Are there any methods or plugins that allow me to transform a directory with files and other directories inside (including if I hear something inside them) into an object in python?

I want to pass a list with all the files and directories of a specific path, with name, size and its complete path, is there any simple way to do it? What would be the best way to resolve this?

exemple:

/app
 -file1
 -file2
 -dir1
  -dir2
   -file3
  -file4

to:

    obj=[
      {name=file1, size= 10kb, path='/app/file1'},
      ...,
      {name=dir1, size= 100kb, path='/app/dir1', child={name=file4, size= 10kb, path='/app/file4'} ,...}  
    ]

1 Answers1

1

There are two python functions that are useful for traversing files in a directory.

os.walk() will recursively walk all files and directories in a given file, and give you a lot of control about the traversal.

os.listdir() is a much simpler function that just returns a list of all the file names in a directory.

I used os.listdir in a recursive function to create the structure you described:

import os

def list_files(directory):
    files = []
    for f in os.listdir(directory):
        file_path = os.path.join(directory, f)
        file = {
            "name": f,
            "size": os.path.getsize(file_path),
            "path": file_path,
        }
        if os.path.isdir(file_path):
            file["children"] = list_files(file_path)
        files.append(file)
    return files

print( list_files("my/directory") )

QuinnFreedman
  • 2,242
  • 2
  • 25
  • 42