Using try-catch to handle multiple possible file types?
rosuav at gmail.com
Tue Nov 19 08:22:50 CET 2013
On Tue, Nov 19, 2013 at 6:13 PM, Victor Hooi <victorhooi at gmail.com> wrote:
> 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?
It's fairly common to work that way. But you may want to be careful
what order you try them in; some codecs might be technically capable
of reading other formats than you wanted, so start with the most
Alternatively, looking at a file's magic number (either with
python-magic/libmagic or by manually reading in a few bytes) might be
more efficient. Either way can work, take your choice!
More information about the Python-list