【问题标题】:concatenate paths for linux and windows at the same time同时连接linux和windows的路径
【发布时间】:2012-06-21 16:08:56
【问题描述】:

我有一个脚本 (python) 应该构建两个路径 - 一个是 Linux 形式(本地),另一个是 Windows 形式(Windows 共享)

如果重要的话,脚本在 Linux 下运行。

os.path 对 Windows 路径没有帮助。对于这种情况,python 有帮助吗?

任何消除额外分隔符的智能连接都将有助于...

【问题讨论】:

  • 好吧,os.path.join 将使用 os.path.sep,在 Linux 的情况下是 '/',但 '/' 也可以在 Windows 下工作(我认为是 XP 起)编辑:您的意思是与 FQNP 或其他东西共享 SMB?

标签: python path concatenation


【解决方案1】:

您可以导入和使用特定于操作系统的路径实现:

import ntpath, posixpath

assert ntpath.join("a", "b") == r"a\b"
assert posixpath.join("a", "b") == "a/b"

当您导入 os.path 时,它会检查当前操作系统以决定使用哪些模块,但您可以根据需要直接使用它们。

【讨论】:

    【解决方案2】:

    根据您所在的平台,os 模块将使用import ntpath as path (Windows) 或import posixpath as path (*nix)。您可以直接导入这些模块来进行路径操作,就像您在不同的平台上一样:

    In [1]: import ntpath
    
    In [2]: ntpath.join('dir', 'file')
    Out[2]: 'dir\\file'
    
    In [3]: import posixpath
    
    In [4]: posixpath.join('dir', 'file')
    Out[4]: 'dir/file'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 2020-10-05
      • 2014-01-27
      • 2016-01-26
      相关资源
      最近更新 更多