【问题标题】:TypeError: coercing to Unicode: need string or buffer, PosixPath foundTypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 PosixPath
【发布时间】:2020-01-11 10:29:45
【问题描述】:

我通过提供 PosixPath 的路径来打开一个文件。

from pathlib import Path

SOURCE_DIR = Path(__file__).resolve().parent.parent.parent  
ROOT_DIR = SOURCE_DIR.parent
DATA_DIR = ROOT_DIR / "data"

with open(DATA_DIR / "filename.txt", "r") as f:
    VALUES = [line.strip() for line in f.readlines()]

我收到以下错误:TypeError: coercing to Unicode: need string or buffer, PosixPath found

如何将整个路径转换为字符串(来自 PosixPath)或打开 PosixPath 文件?

【问题讨论】:

    标签: python python-2.7 path


    【解决方案1】:

    您需要将Path 转换为字符串。只需这样做:

    open(str(DATA_DIR / "filename.txt"), "r")
    

    或者,您可以使用Path.open

    with (DATA_DIR / "filename.txt").open() as f:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 2015-02-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-04
      相关资源
      最近更新 更多