【问题标题】:os.path.join fails with "TypeError: object of type 'LocalPath' has no len()"os.path.join 失败并显示“TypeError:'LocalPath' 类型的对象没有 len()”
【发布时间】:2015-01-17 23:36:53
【问题描述】:

尝试在 pytest 测试中使用“tmpdir”时出现此错误。

TypeError: 'LocalPath' 类型的对象没有 len()

【问题讨论】:

    标签: python pytest os.path


    【解决方案1】:

    'tmpdir' 是<class 'py._path.local.LocalPath'> 类型,传递给os.path.join 时只需将'tmpdir' 包裹在一个字符串中

    示例:

    os.path.join(str(tmpdir), 'my_test_file.txt')

    【讨论】:

    • 甚至:str(tmpdir / 'my_test_file.txt')
    【解决方案2】:

    或者,您可以直接访问 LocalPath 的字符串形式作为属性。

      os.path.join(tmpdir.strpath, 'my_test_file.txt')
    

    我曾经认为使用属性访问意味着您不会将对象转换为字符串,因此效率更高,但我认为我的假设是错误的,但是我更喜欢这种风格,更容易编写恕我直言

    【讨论】:

      猜你喜欢
      • 2016-06-06
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 2018-06-11
      • 2019-05-23
      • 2013-04-18
      • 2015-01-21
      • 2021-12-19
      相关资源
      最近更新 更多