Home > other >  Writing random numbers in file
Writing random numbers in file

Time:03-28

My task is to generate different files and each of them has a specific size. This size includes random numbers that are written in the file. As an example, if the size is 100, it means the program needs to write 100 random numbers and generate a file and add them to that file. My problem is that by running this code I will get for example 100 numbers but they are all the same and non of them is different. Can you help me how to fix it?

import random
import time

def fillFile(fileSize, fileName):
    for i in range(fileSize):
        values = random.randint(0, fileSize   1000)
    file = open(fileName   ".txt", "w")
    for i in range(fileSize):
        file.write(f"{i} {values}\n")

fileSizes = [1000, 5000, 10000, 25000, 50000, 100000, 200000]

def readFile(fileName):
    files= open(str(fileName)   ".txt", "r")
    values = []
    for line in files:
        values.append(line.split())
    return values

CodePudding user response:

Basically you should change the position at which you declare the variable "values"

def fillFile(fileSize, fileName):
    for i in range(fileSize):
        file = open(fileName   ".txt", "w")
        for i in range(fileSize):
            values = random.randint(0, fileSize   1000)
            file.write(f"{i} {values}\n")

The idea here is that in your original code you generate a random number "values" fileSize times, then you enter a loop in which you write the last generated "values" to your file. Where as for your purpose, if you want all numbers in the file to be randomly generated, then you need to either have them declared INSIDE the loop, or to pre-create an array of your numbers and find a way to write it in the format you want in your file.

Note :

As a reminder, the function random.randint(a, b) returns a random integer N such that a <= N <= b. Therefore in your original code values = random.randint(0, fileSize 1000) while generate one random int between a=0 and b=fileSize 1000. Therefore you probably might want to take out the " 1000" I think, but again depends on your goal which I'm unclear about.

CodePudding user response:

You can use the code below as the replacement of your fillFile function:

for fileSize in fileSizes:
    with open(f'{fileSize}.txt', 'w') as fp:
        pop = range(0, fileSize   1000)
        print(*random.choices(pop, k=fileSize), sep='\n', file=fp)

About your error: for each iteration, you override your file. You should use:

def fillFile(fileSize, fileName):
    with open(fileName   ".txt", "w") as file:
        for i in range(fileSize):
            # your code
            ...
  • Related