[Tutor] Text processing with files

Erik Price erikprice at mac.com
Sun Oct 26 07:15:49 EST 2003


On Saturday, October 25, 2003, at 11:48  PM, Daniel Ehrenberg wrote:

> I
> wrote a script but all it did was blank the file. It
> is posted below.
>
> from os import linesep
> filepath = raw_input("Convert which file? ")
> fileread = file(filepath, "r")
> filewrite = file(filepath, "w")
> text = fileread.read()
> fileread.close()
> fixedtext = text.replace('\n', linesep)
> filewrite.write(fixedtext)
> filewrite.close()
>
> What's wrong with it?

When you open a file for writing using file(filepathe, 'w'), Python 
wipes out the contents of the file.  You're doing this before you 
actually read through the file and store its contents into the "text" 
variable.  So, if you simply move your line "filewrite = file(filepath, 
'w')" line down below "fileread.close()" you should be fine.

In other words, close the file from reading before opening it for 
writing.


Erik




More information about the Tutor mailing list