簡體   English   中英

在while循環中用Python寫入文件

[英]Writing to a file in Python in a while loop

我有一個while循環,要求用戶輸入以產生新的種群。 我希望它在每次循環運行時都將填充寫入文本文件,並替換其中已經存在的內容。 我在讀寫文件方面沒有太多經驗。 我想知道是否有人可以幫助我糾正這個問題?

f = open('thesis.txt', 'w')
while True:
    x=input("\n\nhave you found your final individual (y/n)?")
    if x=='y':
        final=int(input("Which individual is your final one?"))
        print("your final individual is a dictionary as follows:")
        print(population[final-1])
        break;
    elif x=='n':
        print("\nto continue you need to select 2 of your favorie  designs.\n")
        report=[0,0]
        report[0]=int(input("the number of your first favorite design?"))
        report[1]=int(input("the number of your second favorite design?"))
        population=step(population,report)
        f.write(str(population))
        print("please copy and paste the following population in grasshopper.\n")
        print(population)

類似於以下內容的實現將起作用:

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語句中的邏輯完成后,文件將更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM