[英]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: 我创建了一组6个随机整数,我希望将其中的500个写入文本文件,以便在文本文件中看起来像这样:
x, x, xx, x, xx, x \\nx, x, x, xx, x, x ....etc x,x,xx,x,xx,x \\ nx,x,x,xx,x,x .... etc
(where x is an integer) (其中x是整数)
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? 是否有比粘贴最后一行500次更简单的方法?
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.
很抱歉,这对你们来说是一个基本问题,但对于学习python的人却不是。
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()))
Iterate over a sufficiently-large generator. 迭代足够大的生成器。
for linenum in xrange(500):
...
Use a for-loop
: 使用
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: 如果您希望每行有6个:
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)
Surely we have simple way :) 当然,我们有简单的方法:)
from random import randint
def rn():
return randint(1, 49)
for i in xrange(500):
print rn()
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.