Search code examples
pythonwindowsshelvepathlib

using pathlib to open shelved files in python


I use pathlib to open textfiles that exists in a different directory, but get this error

TypeError:`"Unsupported operand type for +:'WindowsPath' and 'str'" 

when I try opening a shelved file that exist in a score folder in the current directory like this.

from pathlib import *
import shelve

def read_shelve():
    data_folder = Path("score")
    file = data_folder / "myDB"
    myDB = shelve.open(file)
    return myDB

What am I doing wrong or is there another way to achieve this?


Solution

  • shelve.open() requires filename as string but you provide WindowsPath object created by Path.

    Solution would be to simply convert Path to string following pathlib documentation guidelines:

    from pathlib import *
    import shelve
    
    def read_shelve():
        data_folder = Path("score")
        file = data_folder / "myDB"
        myDB = shelve.open(str(file))
        return myDB