【问题标题】:Expected type 'Union[str, PathLike[str]]', got 'None' instead预期类型'Union [str,PathLike [str]]',改为'None'
【发布时间】:2021-06-21 14:29:50
【问题描述】:

我想解析一个开放存取的数据集。

def parse():
    zipurl = 'xyz'
    with tempfile.NamedTemporaryFile(zipurl) as tfile:
    # Write the contents of the file into the temporary file
    tfile.write(zipurl.read())
    # Set the file's current position at the offset
    tfile.seek(0)
    # Unpack the archive file in the parent directory
    parent = Path(unpack_archive(tfile.name, '/tmp/dataset', format='zip')).parent)

    for file in parent.iterdir():
            if file.is_file():
                old_name = file.stem
                extension = file.suffix
                directory = file.parent

错误: 预期类型 'Union[str, PathLike[str]]',改为 'None'

错误是在parent = Path(unpack_archive(tfile.name, '/tmp/dataset', format='zip')).parent)提出的

我的pycharm版本是Edu 2021.1.1

【问题讨论】:

  • 你有什么pycharm版本?在哪一行发出警告?

标签: python python-3.x pycharm


【解决方案1】:

您混淆了文件路径(字符串)和文件对象(复杂对象)。

import tempfile
from pathlib import Path

with tempfile.NamedTemporaryFile() as temp_file:
    print(f"type: {str(type(temp_file))}")
    print(f"name: {temp_file.name}")
    parent = Path(temp_file.name).parent
    print(f"parent: {str(parent)}")
    for file in parent.iterdir():
        print(f"sibling: {str(file)}")

为我打印:

type: <class 'tempfile._TemporaryFileWrapper'>
name: C:\Users\LENORMJU\AppData\Local\Temp\tmpssxs7qwk
parent: C:\Users\LENORMJU\AppData\Local\Temp
sibling: C:\Users\LENORMJU\AppData\Local\Temp\07379b78-601f-4cf3-bc73-427d7254d49a.tmp.ico
sibling: C:\Users\LENORMJU\AppData\Local\Temp\0b5d3696-4fc7-4823-bacb-dc7988ef3190.tmp.ico
...

错误是Expected type 'Union[str, PathLike[str]]', got 'IO[Union[Union[str, bytes], Any]]' instead,这意味着pathlib.Path 需要一个字符串或类似路径,但你给它的是一个文件对象(称为IO[Union[str, bytes]])。

你的错误是给出一个文件对象而不是一个字符串(文件的路径)。

我认为您应该迭代 Path('/tmp/dataset'),这是提取 zip 的位置,而不是 Path(tfile)(这是 zip 内容)。

【讨论】:

  • with tempfile.NamedTemporaryFile(zipurl) as tfile: tfile.write(zipurl.read()) tfile.seek(0) parent = Path(unpack_archive(tfile.name, '/tmp/dataset', format='zip')).parent for file in parent.iterdir(): ........ 循环前行出错:预期类型为 'Union[str, PathLike[str]]',得到的是 'None'
  • parent = Path(tfile.name).parent
  • 会自动解压文件吗?还是在那之后我需要打开包装?
  • 两者都做:将 zip 解压缩到 '/tmp/dataset' 目录,然后使用 for file in Path('/tmp/dataset').iterdir() 对其进行迭代。因为您硬编码了提取文件的路径,所以不需要parent here。如果您决定不再对提取路径进行硬编码,请提出一个新问题。
  • 如果我选择不进行硬编码,我该如何解决?您介意根据我上面的代码提供示例解决方案吗?我是 python 新手。谢谢
猜你喜欢
  • 1970-01-01
  • 2021-11-07
  • 2017-11-12
  • 2020-07-21
  • 1970-01-01
  • 1970-01-01
  • 2014-07-20
  • 2019-01-14
  • 2020-08-29
相关资源
最近更新 更多