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

问题描述 投票:1回答:1

我使用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

我在做错什么,还是有另一种方法可以做到这一点?

python windows shelve pathlib
1个回答
0
投票

[shelve.open()要求文件名作为string,但您提供由WindowsPath创建的Path对象。

解决方案是按照pathlib documentation准则简单地将Path转换为字符串:

from pathlib import *
import shelve

def read_shelve():
    data_folder = Path("score")
    file = data_folder / "myDB"
    myDB = shelve.open(str(file))
    return myDB
© www.soinside.com 2019 - 2024. All rights reserved.