在尝试使用pytest测试中的“tmpdir”时出现了此错误。
TypeError: 类型为'LocalPath'的对象没有len()
'tmpdir' 的类型是 <class 'py._path.local.LocalPath'>
,在传递给 os.path.join
时只需使用字符串包装 'tmpdir'。
例如:
os.path.join(str(tmpdir), 'my_test_file.txt')
或者,您可以直接访问LocalPath的字符串形式作为属性。
os.path.join(tmpdir.strpath, 'my_test_file.txt')
我曾经认为使用属性访问方式意味着不需要将对象转换为字符串,因此更加高效,但是我觉得我的这个假设是错误的。然而,我个人比较喜欢这种写法,因为它更容易书写。
str(tmpdir / 'my_test_file.txt')
。 - Bruno Oliveira