[Tutor] Unpack requires a string argument of length 8

Marc Tompkins marc.tompkins at gmail.com
Mon May 2 22:17:30 CEST 2011


On Mon, May 2, 2011 at 12:36 PM, Susana Iraiis Delgado Rodriguez <
susana.delgado_s at utzmg.edu.mx> 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.

Now, it seems to me that whoever wrote the dbf module could have done a
little error-checking or -trapping... but this is how I would go about
working with the existing module.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110502/a6c7ecc8/attachment.html>


More information about the Tutor mailing list