简体   繁体   中英

How can I generate random files with random sizes?

I want to generate random files with different sizes from a list of values that states the file size for my assignment.

For example: from this list of numbers [500, 1000, 2000, 3000, 4000] I want to randomly select one of them and generate a file with that size in bytes made up of random letters.

I can randomly select an element from this list but how can I use this to generate files with the selected size.

import random

file_sizes = ['500', '1000', '2000', '3000', '4000']
random_sizes = random.randint(0,len(file_sizes)-1)

print(file_sizes[random_sizes])

I also know how to open a file:

f = open("test.txt", "a")
f.write("test")
f.close()

I want to name the file the same as its file size so maybe I could use a function but Im not sure.

Here's how you can generate a file like that:

from random import choice
from string import ascii_letters as alphabet

file_sizes = [500, 1000, 2000, 3000, 4000]

with open('random.txt', 'w') as f:#This creates a new file
    for i in range(0, choice(file_sizes)):
        f.write(choice(alphabet))

The reason this works is because each character takes up one byte. I've tried it and it woks on my computer. You can always update the alphabet list to add more variation into your file. One example is to add special character like $. That's as much as I can help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM