2

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?

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
Chiebukar
  • 83
  • 9
  • Apparently `shelve.open` hasn't been updated to support input paths based on the `__fspath__` protocol. So you'll have to manually pass `os.fspath(file)` instead of `file`. – Eryk Sun Apr 23 '20 at 17:38

1 Answers1

1

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
Dinko Pehar
  • 5,454
  • 4
  • 23
  • 57