Sometimes you need to generate files with random content for testing purposes. Here's a practical example of how to do this in Python.
The script allows you to specify a list of file sizes and automatically creates those files with random content. It also generates a list variable containing all the created filenames for further processing.
First, specify the sizes of files you want to create (in MB):
FILESIZE_LIST = [0.128, 0.256, 0.512, 1, 2, 4]
Here's the complete function to generate random files:
import os
from decimal import Decimal
def create_files(FILESIZE):
global listofObjectstobeanalyzed
listofObjectstobeanalyzed = []
extensions = ['.jpg', '.png']
for increment in FILESIZE:
print("*** DEBUG *** filesize_%sMB.txt" % (str(increment)))
filename = "filesize_%sMB.txt" % (str(increment))
inc = Decimal(increment)
with open(filename, 'w') as f:
for i in range((inc * 2**20) // 512):
f.write(os.urandom(512))
f.close()
onemoreObject = filename
listofObjectstobeanalyzed.append(onemoreObject)
print("*** DEBUG *** ", onemoreObject, " ADDED to FILE LIST")
print("*** DEBUG *** FINAL LIST: ", listofObjectstobeanalyzed)
return listofObjectstobeanalyzed
Call the function with your file size list:
create_files(FILESIZE_LIST)
FILESIZE_LIST(increment * 2**20) / 512)os.urandom(512)listofObjectstobeanalyzed listThe script generates files with names like:
filesize_0.128MB.txtfilesize_0.256MB.txtfilesize_0.512MB.txtfilesize_1MB.txtfilesize_2MB.txtfilesize_4MB.txtThis approach is useful for testing file upload functionality, storage solutions, or any scenario where you need test files of specific sizes with random content.