Search code examples
python-3.xnumpywhile-loopnested-loops

How do I clear my randomly generated data to create new data in each file in a loop?


I've boiled down the logic of something I'm struggling to figure out (new to Python, been a long time since I've done any coding). I have the code below, the intention is to roll a d6 limit times (in this case 300) and then over a defined number of iterations generate a file with the resulting dice rolls for each 300 iterations into its own file.

What I get is n (loops) files with the same data in each one. So right now this will return random1.txt, random2.txt and random3.txt and all will have the same values in them.

Obviously I need to reinitialize resultsin some way at the start of each iteration of the parent while loop (while loops >=1:), I just can't figure out how.

If anyone can take pity on a blundering artist I'd appreciate it! This is part of an art project I'm working on to make generative art with an axidraw if anyone is curious.

import numpy as np
import os

loops = 3  # will generate n files
limit = 300    
throw = 1.0        
results = []

while loops >=1:
    loops -= 1
    while throw <= limit:   
        roll = np.random.randint(1, 7)
        throw += 1
        results.append(roll)

    n = 1
    while os.path.exists("random%s.txt" % n):
        n += 1

    listToStr = ' '.join(map(str, results))
    f = open("random%s.txt" % n, "w" )
    f.write(listToStr)
    f.close()

Solution

  • Some code for a blundering artist :-)

    import numpy as np
    
    nRolls = 8
    for f in [1,2,3]:
        # Generate 8 rolls of the die
        rolls = np.random.randint(1,7,nRolls)
        # Save like a CSV
        np.savetxt(f'random{f}.txt', [rolls], delimiter=',', fmt='%d')
    

    random1.txt

    5,2,3,5,4,6,6,1
    

    random2.txt

    1,6,6,1,1,4,2,1
    

    random3.txt

    5,4,4,4,6,3,1,5