[Tutor] file.write() blocking
johnp at HomeLumber.com
Thu Mar 25 10:34:22 EST 2004
Well thanks for ruining my morning!
I thought adding the '+' to a 'w' mode wouldn't truncate the file if it already existed. I was quite spectacularly wrong! You have to use 'r+' if you want to open an existing file and write to it without wiping out the original contents. Which is exactly what the python documentation says it will do. Damned tricky of them! There's also an 'a' mode for appending but apparently it's effects can vary with the operating system.
From: Jonathan Hayward [mailto:jsh47 at cam.ac.uk]
Sent: Thursday, March 25, 2004 3:59 AM
To: John Purser
Subject: Re: [Tutor] file.write() blocking
John Purser wrote:
>I haven't played with the code but at a guess I'd say you were creating a new file every time you run this code. I think you want to change that "w" mode to "w+"
What's the exact difference between w and w+?
>I've never tried to write a zero length string to a file and that could also be an issue.
>What platform and verison of Python are you using?
>From: Jonathan Hayward [mailto:jsh47 at cam.ac.uk]
>Sent: Wednesday, March 24, 2004 6:46 AM
>To: tutor at python.org
>Subject: [Tutor] file.write() blocking
> def save_entry(self, text, filename):
> debug_log("Reached 1")
> debug_log(DOCUMENT_ROOT + "entries/" + filename)
> output_file = file(DOCUMENT_ROOT + "entries/" + filename, "w")
> debug_log("Reached 2")
> debug_log("Reached 2.5")
> debug_log("Reached 3")
> debug_log("Reached 4")
>When I get to this point in my code, it prints, "Reached 2" and hangs on
>file.write(""). The output directory has a zero-byte file created. When
>I try analogous test code from Python interactively, it works; does
>anyone see the glitch in this? (The text is a small webpage.)
++ Jonathan Hayward, jonathan.hayward at pobox.com
** To see an award-winning website with stories, essays, artwork,
** games, and a four-dimensional maze, why not visit my home page?
** All of this is waiting for you at http://JonathansCorner.com
More information about the Tutor