【问题标题】:Write text into a file with a loop使用循环将文本写入文件
【发布时间】:2018-04-02 13:32:29
【问题描述】:

我有生成名称的名称生成器。所以我想打开一个文件“名称” 然后将名称写入其中并保存并循环此过程。但它不能正常工作。它打开文件并输入一个名称并关闭它。然后再次打开它并用新词替换旧词。但我希望它将所有生成的名称放入其中,并在将 100 个生成的单词写入文件后保存。我对它很陌生,所以我真的不知道该怎么做。 这是我的代码:

import random
import string 
def run_bot():
    x1 = random.choice(string.ascii_uppercase)
    x2 = random.choice(string.ascii_lowercase)
    x3 = random.choice(string.ascii_lowercase)
    x4 = random.choice(string.ascii_lowercase)
    x5 = random.choice(string.ascii_lowercase)
    name = str(x1 + x2 + x3 +x4 +x5)
    print(name)
    f = open('names', 'w')
    f.write(name)
while True:
for i in range(5):
    run_bot

【问题讨论】:

  • 使用追加模式:f = open('names', 'a')。写入模式将覆盖任何以前的内容并在之后添加新内容。
  • 谢谢工作。但是你知道一种在他们之间写单词的方法吗?这样会更容易阅读,因为现在它们都在一行中,没有任何空格,但再次感谢 :D
  • @bot_diyar print(name,file=f)
  • @bot_diyar 抱歉延迟回答。您现在可能应该已经弄清楚了,但是您可以这样做:f.write(name + '\n')。或者听从@SmartManoj 的建议。

标签: python python-3.x file loops writing


【解决方案1】:

来自 cmets 解决方案的代码。

import random
import string 

def generate_name():
    x1 = random.choice(string.ascii_uppercase)
    x2 = random.choice(string.ascii_lowercase)
    x3 = random.choice(string.ascii_lowercase)
    x4 = random.choice(string.ascii_lowercase)
    x5 = random.choice(string.ascii_lowercase)
    name = str(x1 + x2 + x3 +x4 +x5)
    return name

f = open('names', 'w')
for i in range(5):
    name = generate_name()
    print(name)
    f.write(name + '\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多