-2

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
2

1 Answer 1

-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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm pretty sure the asker wants to display text as shown in the question, not create actual files/folders.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.