[Tutor] Text processing with files

David Rock david at graniteweb.com
Sun Oct 26 13:04:48 EST 2003


* Erik Price <erikprice at mac.com> [2003-10-26 07:15]:
> 
> 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.

You may also want to look into the Module fileinput. It is an iterator
for input streams (including files). One nice thing it has is the
ability to make changes inplace, similar to perl's -i option.

http://www.python.org/doc/current/lib/module-fileinput.html

-- 
David Rock
david at graniteweb.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20031026/a424f07f/attachment.bin


More information about the Tutor mailing list