Sometimes you need to generate files with random content for testing purposes. Here's a practical example of how to do this in Python.

Overview

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.

Implementation

Define File Sizes

First, specify the sizes of files you want to create (in MB):

FILESIZE_LIST = [0.128, 0.256, 0.512, 1, 2, 4]

Create the Function

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

Execute the Function

Call the function with your file size list:

create_files(FILESIZE_LIST)

How It Works

  1. Loop through sizes: The function iterates through each size in FILESIZE_LIST
  2. Calculate iterations: It calculates how many 512-byte chunks are needed to reach the target size (using (increment * 2**20) / 512)
  3. Generate random data: Each iteration writes 512 bytes of random data using os.urandom(512)
  4. Track files: Each created file is added to the listofObjectstobeanalyzed list
  5. Return list: The function returns the complete list of created files for further processing

Output

The script generates files with names like:

  • filesize_0.128MB.txt
  • filesize_0.256MB.txt
  • filesize_0.512MB.txt
  • filesize_1MB.txt
  • filesize_2MB.txt
  • filesize_4MB.txt

This approach is useful for testing file upload functionality, storage solutions, or any scenario where you need test files of specific sizes with random content.