Using try-catch to handle multiple possible file types?

Mark Lawrence breamoreboy at yahoo.co.uk
Tue Nov 19 20:50:02 EST 2013


On 20/11/2013 00:30, Victor Hooi wrote:
> Hi,
>
> Is either approach (try-excepts, or using libmagic) considered more idiomatic? What would you guys prefer yourselves?
>
> Also, is it possible to use either approach with a context manager ("with"), without duplicating lots of code?
>
> For example:
>
> try:
> 	with gzip.open('blah.txt', 'rb') as f:
> 		for line in f:
> 			print(line)
> except IOError as e:
> 	with open('blah.txt', 'rb') as f:
> 		for line in f:
> 			print(line)
>
> I'm not sure of how to do this without needing to duplicating the processing lines (everything inside the with)?
>
> And using:
>
> try:
> 	f = gzip.open('blah.txt', 'rb')
> except IOError as e:
> 	f = open('blah.txt', 'rb')
> finally:
> 	for line in f:
> 		print(line)
>
> won't work, since the exception won't get thrown until you actually try to open the file. Plus, I'm under the impression that I should be using context-managers where I can.
>
> Also, on another note, python-magic will return a string as a result, e.g.:
>
> gzip compressed data, was "blah.txt", from Unix, last modified: Wed Nov 20 10:48:35 2013
>
> I suppose it's enough to just do a?
>
>      if "gzip compressed data" in results:
>
> or is there a better way?
>
> Cheers,
> Victor
>
> On Tuesday, 19 November 2013 20:36:47 UTC+11, Mark Lawrence  wrote:
>> On 19/11/2013 07:13, Victor Hooi wrote:
>>
>>>
>>
>>> So basically, using exception handling for flow-control.
>>
>>>
>>
>>> However, is that considered bad practice, or un-Pythonic?
>>
>>>
>>
>>
>>
>> If it works for you use it, practicality beats purity :)
>>
>>
>>
>> --
>>
>> Python is the second best programming language in the world.
>>
>> But the best has yet to be invented.  Christian Tismer
>>
>>
>>
>> Mark Lawrence

Something like

for filetype in filetypes:
   try:
     process(filetype)
     break
   except IOError:
     pass

??? as it's 01:50 GMT and I can't sleep :(

-- 
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence




More information about the Python-list mailing list