user2519572
user2519572

Reputation: 61

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 ....etc

(where x is an integer)

from random import shuffle, randint

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

print "Random numbers are: " , rn(), rn(), rn(), rn(), rn(), rn()

There must be an easier way than pasting the last line 500 times?

EDIT: Why all the down votes? I'm sorry if this is a basic question for you guys but for someone learning python it's not.

Upvotes: 1

Views: 15571

Answers (5)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Use a for-loop:

from random import shuffle, randint

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

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

If you want 6 of them on each line:

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

Upvotes: 0

jh314
jh314

Reputation: 27792

How about this:

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

If you want to write to text file:

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

Upvotes: 3

Jon Clements
Jon Clements

Reputation: 142146

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:

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

Upvotes: 0

number5
number5

Reputation: 16443

Surely we have simple way :)

from random import randint

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

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

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

Iterate over a sufficiently-large generator.

for linenum in xrange(500):
   ...

Upvotes: 0

Related Questions