Python newbie with a problem writing files

Jason tenax.raccoon at gmail.com
Mon Sep 4 11:16:24 EDT 2006


limodou wrote:
> > Code:
> >
> > import feedparser
> > from xml.sax import saxutils
> >
> > feed_number=200
> >
> > feed_list = open("feed_listing.conf","r")
> > for each_feed in feed_list:
> >     data=feedparser.parse(each_feed)
> >     feed_title=data.entries[0].title
> >     xml_output=open("xml_data\\feed" + str(feed_number) + ".xml", "w")
>
> Maybe there is a extra '=', if it should be:
>
> xml_output.write(feed_title)
>
> ?
>

It took me a few moments to parse what limodou wrote here, but he's
absolutely correct.  Your problem is that you are trying to reassign
the write method in your file.  File objects are built-in types, and do
not allow their methods to be calvaliery replaced.

Here's an example on the correct way (and your way) of writing to a
file:
>>> f = open('spam.xml', 'w')
>>> f.write( 'This data is written to the file' )
>>> f.write = ("This is not a valid Python syntax")
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'file' object attribute 'write' is read-only
>>>

You'll notice that the AttributeError describes exactly what's wrong in
this case.  The write method on your file attribute is read-only.  It
doesn't say anything about whether your file is read-only.

If you really, really want to change the write method into a string,
you can subclass from the file class:

>>> class MyFileType(file):
...     pass
...
>>> myfile = MyFileType('spam_and_eggs.xml', 'w')
>>> myfile.write
<built-in method write of MyFileType object at 0x00870B88>
>>> myfile.write = "Gonna replace write method with this string!"
>>> myfile.write
'Gonna replace write method with this string!'
>>>

Of course, you can no longer easily access the original write method
after re-assigning it like that.

(limodou, I thought this might need a little bit of extra explanation
for the original poster.  I apologize if I seem rude here.)

    --Jason




More information about the Python-list mailing list