try except inside a with open

MRAB python at mrabarnett.plus.com
Fri Jul 20 16:27:10 EDT 2018


On 2018-07-20 18:59, Ganesh Pal wrote:
> Dear python Friends,
> 
> 
> I need a quick suggestion on the below code.
> 
> def modify_various_line(f):
>      """ Try modifiying various line """
>      try:
>          f.write('0123456789abcdef')
>          f.seek(5)     # Go to the 6th byte in the file
>          print f.read(1)
>          f.seek(-3, 2) # Go to the 3rd byte before the end
>          print f.read(1)
>          f.write('END')
>      except IOError as e:
>         raise
>      return True
> 
> def h():
>      try:
>          with open('/tmp/file.txt', 'r+') as f:
>               try:
>                   modify_various_line(f)
>               except Exception as e:
>                 print e
>      except IOError as e:
>          print(e)
> 
> h()
> 
> gpal-cwerzvd-1# python ganesh1.py
> 5
> d
> gpal-cwerzvd-1# cat /tmp/file.txt
> 0123456789abcdefEND#
> 
> 
> 
> (1) Can we  use try and expect  in  a 'with open' function as shown in the
> below example code .
> 
Yes.

> (2)  If I hit any other exceptions  say Value-error can I catch them as
> show below
> 
>      try:
>          with open('/tmp/file.txt', 'r+') as f:
>               try:
>                   modify_various_line(f)
>                   value_list = [str(value) for value in somedict.values()]]
>               except (ValueError,IOError) as e:
>                 print e
>      except IOError as e:
> 
> PS:  I don't want to use other way of opening file say file =
> open(“testfile.txt”,”w”)  and also want to retain modify_various_line(f)
> function ,
> 
Yes.


More information about the Python-list mailing list