0

The answer to this question is down in the comments. So for school I've written this program which asks for information about what a person will bring to a LAN-party. This will happen in a loop, so it will ask for every participant until the participant number has reached 256. I've added some code so some lines will be written to a textfile. My problem is, with every participant, so everytime the loop starts from the beginning, the textfile will be replaced. I can't seem to find where to look for the solution. Here's some lines from my code:

uid=0
while uid <= 256:
     fo = open('userID.txt','w')
     print("\nUserID: ",uid)
     fo.write("\nUserID: " + str(uid))
fo.close()
input("")

Now, my textfile will show the uid(user id), that was displayed when I closed the program. So 1 or 5 or 200, but what I want is that it shows everything until I close the program: 0 1 2 3 4 and so on... Enhancing instead of replacing, so to speak.

The writing to a textfile aspect is something I did for fun. I have already handed in the program, but still want to solve my problem. I am a starting programmer, this is the first block of programming I've had.

2 Answers2

1

Dont reopen the file within the loop. Everytime you open a file with 'w' you overwrite the file.

place fo.close() outside the while loop and you will be fine!

uid=0
fo = open('userID.txt','w')
while uid <= 256:
    print("\nUserID: ",uid)
    fo.write("\nUserID: " + str(uid))
    input("")
fo.close()

as suggested in another answer you can use the 'a' write mode (or 'a+' if you need to read as well as write) but be aware that this will append the new data to the file every time you run the program, therefore every programs run results will be recorded one after the other.

hammus
  • 2,602
  • 2
  • 19
  • 37
  • Actually, don't reopen the file in the loop, `w` will truncate it. – Augusto Hack Nov 03 '13 at 23:48
  • Ah okay, I can see my mistake! Thank you very much for answering. :) I tried this approach, but my file was left blank because I closed it before I the loop was finished. (The original code has some more inputs and I never finished the loop while testing) I don't suppose that there is a way to save an unfinished loop to a textfile? – user2950983 Nov 03 '13 at 23:59
  • @user2950983 See the other answer, you can do that. – aIKid Nov 04 '13 at 00:26
1

You can open file in 'a' (append) mode instead of 'w', or open it only once outside of loop. Also you can use fo.flush() to write buffered data to file immediately

more about buffering

Community
  • 1
  • 1