J.Mishra J.Mishra - 18 days ago 5
Python Question

Create files of different sizes inside directories recursively in Python

I'm trying to write a python script which will traverse through a directory recursively and create files of different sizes inside all of them. So far I have reached here. Well I haven't written any mechanism for creating files with different sizes but I need it. I very well know there's something wrong with the file creation logic I have written. Any help is highly appreciable.

My code:

#!/usr/bin/python

import os
import uuid

for dirs in os.walk('/home/zarvis'):
print dirs
filename = str(uuid.uuid4())
size = 1000000
with open(filename, "wb") as f:
f.write(" " * size)

Answer

Don't use a fixed size. Use random.randint to create a random size. Use os.path.join to build the full path to a file.

import os
import uuid
import random

for dirs in os.walk("/home/zarvis"):
    d = dirs[0]
    filename = str(uuid.uuid4())
    size = random.randint(1, 100)
    with open(os.path.join(d, filename), "w") as f:
        f.write(" " * size)