os.path.join失败并显示“TypeError:object of type 'LocalPath' has no len()”

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

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

2个回答

23

'tmpdir' 的类型是 <class 'py._path.local.LocalPath'>,在传递给 os.path.join 时只需使用字符串包装 'tmpdir'。

例如:

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


5
甚至可以这样写:str(tmpdir / 'my_test_file.txt') - Bruno Oliveira

4

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

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

我曾经认为使用属性访问方式意味着不需要将对象转换为字符串,因此更加高效,但是我觉得我的这个假设是错误的。然而,我个人比较喜欢这种写法,因为它更容易书写。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接