使用pathlib打开python中的搁置文件



我使用pathlib打开不同目录中存在的文本文件,但得到了这个错误

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

当我尝试打开当前目录中的分数文件夹中的搁置文件时,如下所示。

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

我做错了什么,或者有其他方法可以做到这一点吗?

shelve.open((要求文件名为字符串,但您提供了由Path创建的WindowsPath对象。

解决方案是简单地按照pathlib文档指南将Path转换为字符串:

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

最新更新