xml.dom - reading from a file

dman at dman13.dyndns.org dman at dman13.dyndns.org
Tue Nov 18 21:08:21 CET 2003


On Tue, 18 Nov 2003 13:58:47 +0000 (UTC), Magnus Lie Hetland wrote:
> In article <bpb1mf$uc1$0 at 216.39.172.122>, Bengt Richter wrote:
>>On Mon, 17 Nov 2003 09:54:37 GMT, Alex Martelli <aleax at aleax.it> wrote:
>>
>>>sashan wrote:
>>>
>>>> Is the way to use DOM for an xml file as follows:
>>>> 1) Read the file into a string
>>>> 2) Call xml.dom.minidom.parseString(string)
>>>
>>>It's one way, but xml.dom.minidom.parse(f) is generally better.  f can
>>>be a filename OR a file object open for reading.
>>>
>>That reminds me ...
>>
>>Is there a BDFL pronouncement or dev consensus on implementation of
>>accepting either filename or file-object?
> [snip]
> 
> The standard in such cases is usually the "leap before you look"
> idiom, I should think, using try/except and catching signature-related
> exceptions. In this case you might try to call read() and revert to
> opening the file if there is no read method.

Another ordering would be to make the parameter a file, without trying
to read first :

def my_function( f ) :
    try :
        f = file(f, "r")
    except TypeError : pass

    f.read()

If 'f' is a valid path, then you'll have an open file.  If it is
already a file you'll get a type error ("coercing to Unicode: need
string or buffer, file found").  If it is neither, then the .read()
will fail.

-- 
Q: What is the difference between open-source and commercial software?
A: If you have a problem with commercial software you can call a phone
   number and they will tell you it might be solved in a future version.
   For open-source sofware there isn't a phone number to call, but you
   get the solution within a day.
 
www: http://dman13.dyndns.org/~dman/            jabber: dman at dman13.dyndns.org




More information about the Python-list mailing list