我想用os.path.basename
编写一个简单的单元测试
def test(path):
return os.path.basename(os.path.normpath(title))
...
result = test('/path/foo')
assert result == 'foo'
result = test(r'c:\Users\Foo\Documents\foo')
assert result == 'foo'
在linux上运行第二个测试(windows路径)失败。
我想第一个测试在windows上会失败。
这实际上很有意义,因为存在不同的os.path
模块
Since different operating systems have different path name conventions, there are several versions of this module in the standard library.
有没有方法可以导入os.path
的特定版本?
我已经尝试将sys.platform
设置为win32
当然,我可以检查当前的平台,只运行两个测试中的一个——但我想知道是否有一种方法可以同时运行这两个测试。在
您应该始终使用
/
作为路径分隔符。Python会将其转换为适合您平台的正确分隔符。在\
用于启动转义序列。使用/
可以避免使用原始字符串来禁用\
转义序列(如您文章中的第二个字符串所示)。在在原始字符串中使用
\
也可能导致os.path
方法的行为异常(并且只适用于Windows平台)。在相关问题 更多 >
编程相关推荐