打开 Path 对象时 Pycharm 类型提示警告

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

使用以下代码:

from pathlib import Path

file = Path("test.txt")

with open(file) as fl:
    pass 

Pycharm 在

file

上给出以下警告
Unexpected type(s): (Path) 

Possible types: 
  (Union[str, bytes, int]) 
  (Union[str, bytes, int, PathLike]) less... (Ctrl+F1) 

Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations.

我做错了什么吗?

python pycharm type-hinting
2个回答
0
投票

您可以使用 Path 函数读取文件,如下所示:

file = Path("test.txt")    
with file.open(mode="r", encoding="utf-8") as fl:
    content = fl.read()

-3
投票

你可以这样使用它

    file = "test.txt"

    with open(file) as fl:
        pass 
  • Pycharm 甚至会提示您可能想要使用的文件。我这样用没有任何问题。
  • 如果您要查找的文件与代码不在同一目录中,您需要添加完整路径
© www.soinside.com 2019 - 2024. All rights reserved.