Skip to content Skip to sidebar Skip to footer

Write Multiple Values Into Text File In Python?

I have created a set of 6 random integers and I wish to write 500 of them into a text file so it looks like this inside the text file: x, x, xx, x, xx, x \n x, x, x, xx, x, x ..

Solution 1:

How about this:

print "Random numbers are: "for _ inxrange(500):
    print rn(), rn(), rn(), rn(), rn(), rn()

If you want to write to text file:

withopen('Output.txt', 'w') as f:
    f.write("Random numbers are: \n")
    for _ inxrange(500):
        f.write("%s,%s,%s,%s,%s,%s\n" % (rn(), rn(), rn(), rn(), rn(), rn()))

Solution 2:

Iterate over a sufficiently-large generator.

for linenum in xrange(500):
   ...

Solution 3:

Surely we have simple way :)

from random import randint

def rn():
    return randint(1, 49)

for i in xrange(500):
    print rn()

Solution 4:

Could use the following:

from random import randint
from itertools import islice

rand_ints = iter(lambda: str(randint(1, 49)), '')
print'Random numbers are: ' + ' '.join(islice(rand_ints, 500))

And dump those to a file as such:

withopen('output', 'w') as fout:
    for i in xrange(500): # do 500 rowsprint >> fout, 'Random numbers are: ' + ' '.join(islice(rand_ints, 6)) # of 6 each

Solution 5:

Use a for-loop:

from random import shuffle, randint

defrn():
    return randint(1,49);

withopen('out.txt', 'w') as f:
    for _ in xrange(500):
        f.write(str(rn()) + '\n')

If you want 6 of them on each line:

withopen('out.txt', 'w') as f:
    for _ in xrange(500):
        strs = "Purchase Amount: {}\n".format(" ".join(str(rn()) 
                                                          for _ in xrange(6)))
        f.write(strs)

Post a Comment for "Write Multiple Values Into Text File In Python?"