列表.拆分()不跨平台?

2024-04-25 19:58:24 发布

您现在位置:Python中文网/ 问答频道 /正文

最近我在用Ubuntu编写代码和在Windows下运行时遇到了一些问题。你知道吗

两个平台上的代码:

enter image description here

输出Ubuntu(这就是我想要的):

enter image description here

输出窗口:

enter image description here

如您所见,windows上的split添加了'/',而不是按'/'拆分列表。list.split()不是跨平台的吗?你知道吗


Tags: 代码列表ubuntuwindows跨平台平台listsplit
3条回答

更“通用”的方法是使用os.path.split()。这将在最后一个分隔符处分割路径。必须迭代或递归地处理第一部分。你知道吗

在Windows下,也可以考虑拆分驱动器号。你知道吗

像这样的

drv, path = os.path.splitdrive(fullpath)
spl = []
while path:
    path, lastpart = os.path.split(path)
    spl.append(lastpart)
spl.append(drv) # as needed
spl.reverse()

应该这样做,但我手头没有窗户,无法测试它。你知道吗

使用os.sep

例如:

import os

importpath = __file__
print(importpath.split(os.sep))

如果你想超级安全,你应该反复使用os.path.split,或者同时测试os.sepos.altsep作为分隔符。你知道吗

__file__将始终使用os.sep,但是当您从其他代码或用户直接输入获得路径时,很可能会使用os.altsep'/'在Windows上)。你知道吗

Windows上的示例:

>>> path = os.path.join('c:\\a', 'c/d')
>>> print(path)
'c:\\a\\c/d'
>>> pathsep = re.compile(r'\\|/')
>>> pathsep.split(path)
['c:', 'a', 'b', 'c']

或者:

 def safe_split(path):
    res = []
    while True:
        path, tail = os.path.split(path)
        if len(tail) == 0:
            break
        res.append(tail)
    res.append(path)           # do not forget the initial segment
    res.reverse()
    return res

以及

>>> safe_split('c:\\a\\c/d')
['c:\\', 'a', 'c', 'd']

相关问题 更多 >