我有一段令人惊叹的代码,我想将输出写入文本文件,但不太确定如何将它自动提供给我的数据写入文本文件?
import random
members = 5
participants=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
random.shuffle(participants)
for i in range(len(participants) // members + 1):
print('Group {} consists of:'.format(i + 1))
group = participants[i*members:i*members + members]
for participant in group:
print(participant)
那么一旦写入,我怎样才能让它从文本文件中读出数据?
感谢您的评论或解答!
要写入文本文件,您必须首先打开该文本文件,Python 使用 open(filename, read or write) 使这变得简单
import random
members = 5
participants=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
random.shuffle(participants)
with open("myfile.txt",'w') as tf:
for i in range(len(participants) // members + 1):
group = participants[i*members:i*members + members]
for participant in group:
tf.write("Group "+str(i+1)+" consists of:"+str(participant))
tf.write("\n")
将每个参与者写在单独的行上。要读回这些内容:
with open("myfile.txt",'r') as tf:
for line in tf.readlines():
print(line)
为了澄清,以下语句写入文件:
with open("myfile.txt",'w') as tf:
tf.write("Some string of text")
tf是一个允许你对文件进行操作的对象
我是一名优秀的程序员,十分优秀!