我正在寻求帮助 我已生成一个随机文本,但我想将此输出保存到新的文本文件中。 有人可以帮我这么做吗?
这是我的代码:
def write_random_text(self, amount):
return re.sub(ur'[^a-zA-Z,. ]', '', u''.join([random.choice(list(self.text)) for i in range(amount)]))
print write_random_text(200)
答案 0 :(得分:0)
# Open/Create a file
with open("file.txt", "a") as file:
# Write in file
file.write("text here")
r =读取
w =写入
a =追加
a:如果该文件已存在,则将此行添加到文件中,否则创建该文件。这个是最常用的。
答案 1 :(得分:0)
除非这是一个类的方法我建议不要使用self:
def write_random_text(self, amount, n):
for i in range(1,n+1):
with open("file{}".format(i),'w') as f:
f.write(re.sub(ur'[^a-zA-Z,. ]', '', u''.join([random.choice(list(self.text)) for i in range(amount)])))
在课堂上使用它会是这样的:
instance.write_random_text(4,3)