【问题标题】:using pathlib to open shelved files in python使用 pathlib 在 python 中打开搁置的文件
【发布时间】:2020-04-23 11:32:23
【问题描述】:

我使用 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 尚未更新以支持基于__fspath__ 协议的输入路径。所以你必须手动传递os.fspath(file) 而不是file

标签: python windows shelve pathlib


【解决方案1】:

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

解决方案是按照pathlib documentation 指南将路径简单地转换为字符串:

from pathlib import *
import shelve

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    相关资源
    最近更新 更多