Using try-catch to handle multiple possible file types?

Amit Saha amitsaha.in at gmail.com
Tue Nov 19 02:22:13 EST 2013


On Tue, Nov 19, 2013 at 5:13 PM, Victor Hooi <victorhooi at gmail.com> wrote:
> Hi,
>
> I have a script that needs to handle input files of different types (uncompressed, gzipped etc.).
>
> My question is regarding how I should handle the different cases.
>
> My first thought was to use a try-catch block and attempt to open it using the most common filetype, then if that failed, try the next most common type etc. before finally erroring out.
>
> So basically, using exception handling for flow-control.
>
> However, is that considered bad practice, or un-Pythonic?
>
> What other alternative constructs could I also use, and pros and cons?
>
> (I was thinking I could also use python-magic which wraps libmagic, or I can just rely on file extensions).
>
> Other thoughts?

How about starting with a dictionary like this:

file_opener = {'.gz': gz_opener,
                     '.txt': text_opener,
                    '.zip': zip_opener}
                   # and so on.

where the *_opener are say functions which does the job of actually
opening the files.
The above dictionary is keyed on file extensions, but perhaps you
would be better off using MIME types instead.

Assuming you go ahead with using MIME type, how about using
python-magic to detect the type and then look in your dictionary
above, if there is a corresponding file_opener object. If you get a
KeyError, you can raise an exception saying that you cannot handle
this file.


How does that sound?

Best,
Amit.


-- 
http://echorand.me



More information about the Python-list mailing list