在while循环中用Python写入文件

时间:2017-03-19 00:07:19

标签: python output file-writing

我有一个while循环,要求用户输入以产生新的人口。我希望它在每次循环运行时将填充写入文本文件并替换已存在的内容。我在阅读和写入文件方面没有太多经验。我想知道是否有人可以帮我纠正这个问题?

55, 1, 23, 45

1 个答案:

答案 0 :(得分:0)

类似于此的实现将起作用:

while True:
    x = input("\n\nhave you found your final individual (y/n)?")
    if x == 'y':
        # do stuff here
        break
    elif x == 'n':
        with open('thesis.txt', 'a') as file:
            # get further user input/do stuff here
            file.write('something\n')

模式“a”打开文件以进行追加,因此写入文件的任何数据都会自动添加到文件末尾。在with语句中的逻辑完成后,该文件将更新。