简体   繁体   English

如何在另一个文本文件python中保存文本

[英]how do I save a text in another text file python

I'm in search for help. 我正在寻求帮助。
I've generated a random text, but I want to save this output onto a new text file. 我生成了一个随机文本,但我想将此输出保存到一个新的文本文件中。 Can someone help me do that? 有人可以帮我吗?

This is my code: 这是我的代码:

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)
# Open/Create a file 
with open("file.txt", "a") as file:
    # Write in file
    file.write("text here")

r = read r =读取
w = write w =写
a = append a =附加

a: Add this line to a file, if that file already exists, else create the file. 答:将此行添加到文件中(如果该文件已存在),否则创建该文件。 This one is the most used. 这是最常用的。

unless this is a method of a class I would suggest not using self: 除非这是一个类的方法,否则我建议不要使用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)])))

Using it in your class would be something like: 在您的班级中使用它就像:

instance.write_random_text(4,3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM