2017-03-19 5 views
0

새로운 입력을 생성하기 위해 사용자 입력을 요청하는 while 루프가 있습니다. 루프가 실행될 때마다 텍스트 파일에 인구를 쓰고 이미 거기에있는 내용을 바꾸기를 원합니다. 필자는 파일을 읽고 쓰는 데 많은 경험이 없습니다. 누군가가이 문제를 바로 잡도록 도와 줄 수 있는지 궁금 해서요?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) 
+0

왜 마지막으로 루프가 실행될 때까지 파일의 내용을 버리시겠습니까? – Denziloe

+1

이 텍스트 파일을 다른 프로그램에서 동시에 읽으므로 루프가 실행될 때마다 업데이트해야합니다. 그러나, 나는 그것을 알아 냈다고 생각한다. 루프에서 파일을 열고 닫아야합니다. –

+0

파일을 연 후에 파일을 닫지 않습니다. 'f = open ('thesis.txt', 'w')'를 실제로 사용하는 곳에 옮길 수 있습니다.이 경우에는'else'를 쓰고, 쓰고 난 후에는'f.close()'를 닫을 수 있습니다. 모든 것이 저장됩니다. – Wright

답변

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 문의 논리가 완료되면 파일이 업데이트됩니다.