gpt4 book ai didi

python - 写入纺织品

转载 作者:太空宇宙 更新时间:2023-11-03 14:51:33 24 4
gpt4 key购买 nike

我有一段令人惊叹的代码,我想将输出写入文本文件,但不太确定如何将它自动提供给我的数据写入文本文件?

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是一个允许你对文件进行操作的对象

关于python - 写入纺织品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com