On Mon, May 2, 2011 at 1:17 PM, Marc Tompkins <[email protected]> wrote: > On Mon, May 2, 2011 at 12:36 PM, Susana Iraiis Delgado Rodriguez > <[email protected]> wrote: >> >> I'm working on getting information that comes from a dbf file (database), >> this dbf file is related to another file in the system, a shapefile. My code >> is trying to get all the dbf name records, but when the systen gets an empty >> file, my code fails: >> Traceback (most recent call last): >> File "<stdin>", line 1, in <module> >> File "get_dbf.py", line 32, in <module> >> dbf = Dbf(d,new=False, readOnly=True) >> File "C:\Python26\lib\site-packages\dbf.py", line 135, in __init_ >> self.header = self.HeaderClass.fromStream(self.stream) >> File "C:\Python26\lib\site-packages\header.py", line 109, in from >> (_cnt, _hdrLen, _recLen) = struct.unpack("<I2H", _data[4:12]) >> struct.error: unpack requires a string argument of length 8 >> >>> >> How can I fix it? > > You said that this happens when you're trying to process an empty file. If > that's the case, then I would certainly expect this: "_data[4:12]" not to > return a string of length 8! > > So you have two options: > - "Get permission" >> >> if (some check to make sure the file isn't empty): >> dbf = Dbf(d,new=False, readOnly=True) > > or > - "Ask forgiveness". >> >> try: >> dbf = Dbf(d,new=False, readOnly=True) >> except: >> (cleanup code to handle aborted file opening) >> > > Which is correct? That depends on your own preference, and also on how > often the error occurs. If you rarely run across empty files, then "ask > forgiveness" makes more sense, since otherwise you waste time checking for > an error that hardly ever happens; on the other hand, if you run into lots > of empty files, then it makes sense to check first, each time.
Also, the first option does leave the possibility of a race condition, however slim that might be. Personally, I'd use the try/except pair, and optimize later if it turned out to be an issue. -- http://neon-buddha.net _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
