Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中将多个值写入文本文件?_Python - Fatal编程技术网

在Python中将多个值写入文本文件?

在Python中将多个值写入文本文件?,python,Python,我已经创建了一组6个随机整数,我希望将其中的500个写入文本文件,因此在文本文件中如下所示: 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())) x、 x,xx,x,xx,x\n x、 x,x,x

我已经创建了一组6个随机整数,我希望将其中的500个写入文本文件,因此在文本文件中如下所示:

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()))
x、 x,xx,x,xx,x\n x、 x,x,xx,x,x…等等

(其中x是一个整数)

一定有比粘贴最后一行500次更简单的方法吗


编辑:为什么所有的反对票?如果这对你们来说是一个基本问题,我很抱歉,但对于学习python的人来说,这不是。

迭代一个足够大的生成器

for linenum in xrange(500):
   ...

对循环使用

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')
如果您希望每行有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)
这个怎么样:

print "Random numbers are: "
for _ in xrange(500):
    print rn(), rn(), rn(), rn(), rn(), rn()
如果要写入文本文件:

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()))

当然我们有一个简单的方法:)


可以使用以下方法:

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))
并将其转储到文件中,如下所示:

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

那太好了,但是我想把它们打印成一个文本文件,我该怎么做呢?e、 g ext_file=open(“Output.txt”,“w”)text_file.write(“购买金额:“'rn(),rn(),rn(),rn(),rn()”)text_file.close()您能告诉我如何按升序排序吗?我尝试了sort()功能,但没有运气。我想人们会建议你先完成一个基本的Python教程:Downvoted,因为你的问题(例如循环)的解决方案可以在最基本的编程教程中找到;这个网站并不是要教你编程的基础知识。在提问之前,您需要自己做一些工作(比如阅读python教程)。好的,谢谢您的帮助。我以后会这么做的,亲爱的。
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