@@ -54,14 +54,23 @@ def __del__(self):
5454 for f in self ._cache .values ():
5555 f .close ()
5656
57- def file_handle (self , path , mode , reopen = False ):
57+ def file_handle (self , path , binary = False ):
5858 """Manages the file handle cache and opening the files in the correct mode"""
5959
6060 if path not in self ._cache :
61- f = open (path , mode , 0 )
62- self ._cache [path ] = f
63- elif reopen :
64- self ._cache [path ].close ()
61+ r_ok = os .access (path , os .R_OK )
62+ w_ok = os .access (path , os .W_OK )
63+
64+ if r_ok and w_ok :
65+ mode = 'a+'
66+ elif w_ok :
67+ mode = 'a'
68+ else :
69+ mode = 'r'
70+
71+ if binary :
72+ mode += 'b'
73+
6574 f = open (path , mode , 0 )
6675 self ._cache [path ] = f
6776 else :
@@ -70,26 +79,16 @@ def file_handle(self, path, mode, reopen=False):
7079 return f
7180
7281 def read (self , path ):
73- f = self .file_handle (path , 'r' )
74-
75- try :
76- f .seek (0 )
77- value = f .read ()
78- except IOError :
79- f = self .file_handle (path , 'w+' , reopen = True )
80- value = f .read ()
82+ f = self .file_handle (path )
8183
82- return value .strip ()
84+ f .seek (0 )
85+ return f .read ().strip ()
8386
8487 def write (self , path , value ):
85- f = self .file_handle (path , 'w' )
88+ f = self .file_handle (path )
8689
87- try :
88- f .seek (0 )
89- f .write (value )
90- except IOError :
91- f = self .file_handle (path , 'w+' , reopen = True )
92- f .write (value )
90+ f .seek (0 )
91+ f .write (value )
9392
9493
9594# -----------------------------------------------------------------------------
@@ -1298,7 +1297,7 @@ def bin_data(self, fmt=None):
12981297 "float" : 4
12991298 }.get (self .bin_data_format , 1 ) * self .num_values
13001299
1301- f = self ._attribute_cache .file_handle (abspath (self ._path + '/bin_data' ), 'rb' )
1300+ f = self ._attribute_cache .file_handle (abspath (self ._path + '/bin_data' ), binary = True )
13021301 f .seek (0 )
13031302 raw = bytearray (f .read (self ._bin_data_size ))
13041303
@@ -1761,7 +1760,7 @@ def __init__(self):
17611760 self ._button_buffer (self ._buttons [b ]['name' ])
17621761
17631762 def _button_file (self , name ):
1764- return self ._file_cache .file_handle (name , 'r' )
1763+ return self ._file_cache .file_handle (name )
17651764
17661765 def _button_buffer (self , name ):
17671766 if name not in self ._buffer_cache :
0 commit comments