Creating a hierarchical file structure in Python with file names and sizes

131 views Asked by At

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
1

There are 1 answers

1
Shaan K On

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.