-1

How to create file tree from list of (str, int)?

I already tried to find ways to solve this problem, but I managed to find code for working with files, not a list of strings.

Example of input:

[
    ('dir1\\file.exe', 14680064)
    ('dir1\\file-1.bin', 4293569534)
    ('dir1\\file-2.bin', 4294967294)
    ('dir1\\file-3.bin', 4294967294)
    ('dir1\\archives\\archive1.zip', 5242880)
    ('dir1\\archives\\archive2.zip', 525788)
]

Result:

dir1
├──file.exe 14680064 Bytes 
├──file-1.bin 4293569534 Bytes 
├──file-2.bin 4293569534 Bytes 
├──file-3.bin 4293569534 Bytes 
└──archives
    ├──archive1.zip 5242880 Bytes
    └──archive2.zip 525788 Bytes
wowlikon
  • 1
  • 2
  • 1
    Does this answer your question? [List directory tree structure in python from a list of path file](https://stackoverflow.com/questions/72618673/list-directory-tree-structure-in-python-from-a-list-of-path-file) – tevemadar May 21 '23 at 22:01
  • 1
    Or https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python – tevemadar May 21 '23 at 22:02

1 Answers1

-1

You could use pathlib for a lot of what you need.

Given your list of paths and file sizes paths.

def generate_file_structure(paths):
    for path_data in paths:
        path, size = path_data

        file_path = Path(path)
        file_dir = file_path.parent
        # Effectively run mkdir -p which creates any directories that don't exist
        file_dir.mkdir(exists_ok=True, parents=True)
        
        # Open the file with wb to indicate you are writing bytes
        with open(file_pathm 'wb') as fp:
            bytes = b'\xff' * size
            fp.write(bytes)

Please note that this function does not generate a valid zip file (or any specific file type), so if that is what you want to do, you'll have to implement that specifically.

Shaan K
  • 356
  • 1
  • 7