繁体   English   中英

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

[英]using pathlib to open shelved files in 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 object。

解决方案是按照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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM