1

So I found this code for solving the Hanoi problem online, but tried modifying the code to save every printed line in a text file. The thing is that I only get one line saved, and I have absolutely no clue as to why. I'm pretty new to this and would appreciate it if anyone feels like answering.

def hanoi(ndisks, startPeg=1, endPeg=3):
    text_file = open("hanoiresults.txt", "w")
    j = 0
    i = j

    if ndisks:
        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
        print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
        text_file.write("Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg) + "\n")
        j +=1
        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg) 
    text_file.close()

hanoi(ndisks=12)
EdChum
  • 376,765
  • 198
  • 813
  • 562

3 Answers3

1

You are opening the file anew on each call to hanoi() and overwriting the contents.

Instead, you should open it once and pass it as a parameter:

def hanoi(ndisks, startPeg=1, endPeg=3, text_file):
    #...
        hanoi(ndisks-1, startPeg, 6-startPeg-endPeg, text_file=text_file)
        #...
        hanoi(ndisks-1, 6-startPeg-endPeg, endPeg, text_file=text_file)
    #...

with open("hanoiresults.txt", "w") as f:
    hanoi(ndisks=12, text_file=f)

Opening in append mode ("a") also works, but then you need to clear the file first and you are needlessly closing and reopening it.

If you don't want to pass a parameter (e.g. due to stack size concerns), you can use a global variable to keep the file open. However, globals are generally frowned upon.

Community
  • 1
  • 1
otus
  • 5,572
  • 1
  • 34
  • 48
0

You have to open the file with the append mode :

text_file = open("hanoiresults.txt", "a")
Pete_Gore
  • 594
  • 1
  • 5
  • 20
-1

Because of this line:

text_file = open("hanoiresults.txt", "w")

You have to open the file in the append mode. Every time your method recurses, it opens the file in the write mode, thereby truncating the contents of the file.

Instead, do a:

text_file = open("hanoiresults.txt", "a")

More on file reading and writing here

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • Wouldn't that be convenient, eh? Someone actually giving constructive criticism? Well, I quite frankly prefered your answer at the time as it answered my question quite simply and let me understand the mistake I made. – user3710101 Jun 05 '14 at 20:17
  • I'm not the original downvoter, but I can see reasons it would have happened. Not all systems allow you to have a file open multiple times simultaneously. Also, I believe output buffering may cause data to be lost if you do this. The other answer is much more reliable. (pinging @user3710101 so he sees this) – user2357112 Jun 06 '14 at 05:54