Search code examples
pythonshelve

get file path of already opened shelve?


Is there any way to find the path and filename of an already opened shelve object?

I looked through the documentation for the shelve but i get the impression that it is more of a wrapper around the backend implementation and i suppose not all backends implement being queried in some way about what file they're working with.


Solution

  • You can get the filename but it's undocumented and could break at any python update:

    >>> d=shelve.open("/some/datafile.shelve")
    >>> d.dict._datfile
    '/some/datafile.shelve.dat'
    

    Why do you need it at all? You have supplied the filename when opening the shelve so can't you not refer back to that original filename? If you really want, you can simply store the filename on the resulting shelve object. This way you can refer to it by the name you gave it yourself, and not depend on the internals of the implementation:

    >>> filename = "/some/datafile.shelve"
    >>> d=shelve.open(filename)
    >>> d.original_filename = filename
    >>> d
    <shelve.DbfilenameShelf object at 0x035A6550>
    >>> d.original_filename
    '/some/datafile.shelve'
    >>>
    

    It does not automatically know about the ".dat" suffix that gets appended though.