I've ran into an error while dealing with a while loop. I am able to input the number I want to run, and the results are written correctly to the corresponding .CSV. Once the section for that number is done running, it will ask if I want to try again with a new number. It runs the new numbers code and creates the new .CSV but the filesize stays at 0kb. I thought this has to do with closing the file once complete but I have written the f#.close() in there.
Ex: Choose number 1, code for #1 runs and saves .CSV correctly, choose Yes for another run and new number (#2), code #2 runs but does not correctly close thus not saving any info to the second CSV.
This happens regardless of which number I choose first or second. (ex: choose 3 first, 3 runs fine and saves fine. Then choosing 2 and runs but does not save correctly.)
Here is my current code:
f1 = file('1.csv', 'rb')
f2 = file('2.csv', 'rb')
f3 = file('3.csv', 'rb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.reader(f3)
number = raw_input("Enter number: ")
while True:
if number == "1":
f4 = file('No_1_Results.csv', 'wb')
c4 = csv.writer(f4)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f4.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #1"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number == "2":
f5 = file('No_2_Results.csv', 'wb')
c5 = csv.writer(f5)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f5.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #2"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number =="3":
f6 = file('No_3_Results.csv', 'wb')
c6 = csv.writer(f6)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f6.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #3"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number is not "1" or "2" or "3":
print "Invalid number selected."
number = raw_input("Please choose a number: ")
continue
f1.close()
f2.close()
f3.close()
Note: Using Python 2.6 on Windows / still learning python -