TypeError:强制转换为Unicode:需要字符串或缓冲区,找到了PosixPath

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

我通过提供路径作为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个回答
1
投票

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

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

或者,您可以使用Path.open

Path.open
© www.soinside.com 2019 - 2024. All rights reserved.