在python中将循环数据输出到文本文档

时间:2014-02-13 22:27:36

标签: python python-3.x

我目前有以下代码:您输入一个字符串,计算机然后拉随机字母并尝试将其与字符串中的字母匹配。这会重复,每次迭代,计算机都会更接近猜测你的字符串。我想输出输入的初始字符串或'目标'以及获得正确匹配所需的迭代次数的字符串格式。我想将其输出到文本文档。到目前为止,脚本生成一个文本文档但不输出到它。我想在主循环的每次迭代后保存数据。我有工作程序,我只需要对输出进行协助,有关如何做到的任何想法?

以下是我取得的进展:

import string
import random

possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:£$^%&*|'

file = open('out.txt', 'w')

again = 'Y'
while again == 'Y' or again == 'y':
    target = input("Enter your target text: ")
    attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
    attemptNext = ''

    completed = False
    generation = 0
    while completed == False:
        print(attemptThis)
        attemptNext = ''
        completed = True
        for i in range(len(target)):
            if attemptThis[i] != target[i]:
                completed = False
                attemptNext += random.choice(possibleCharacters)
            else:
                attemptNext += target[i]
        generation += 1
        attemptThis = attemptNext

    genstr = str(generation)
    print("Target matched! That took " + genstr + " generation(s)")

    file.write(target)
    file.write(genstr)

    again = input("please enter Y to try again: ")

file.close()

1 个答案:

答案 0 :(得分:1)

解决原始问题和评论中的问题:

  • 如何在循环的每次迭代后写入文件:在file.flush()之后调用file.write(...)

    file.write(target)
    file.write(genstr)
    file.flush() # flushes the output buffer to the file
    
  • 要在您编写的每个“target”和“genstring”之后添加换行符,请在字符串中添加换行符(或者您想要的任何其他输出格式):)

    file.write(target + '\n')
    file.write(genstr + '\n')