gpt4 book ai didi

python os.path.dirname 使用 Windows 网络路径产生错误的结果

转载 作者:行者123 更新时间:2023-11-30 23:17:59 24 4
gpt4 key购买 nike

我有这个代码片段

print "tmp = ", tmp
print "dirname = ", os.path.dirname(tmp)
print "tmp sane = ", (os.path.dirname(tmp.replace("\\", "/"))).replace("/", "\\")

产生这个结果

tmp =  \\aaaa.aaa\aaaaaaaa\aaaaaaaaa\aaaa\aaaa\aaaaa\aaaaaaa\aaaaaaa\aaaa.aaaaaaaa_aaaaaa\aa\aaaaa\aaaaaa\aaa\aaaaaa\aa\aaaaa\aaaaaaa_aaaaaaaaa_aaa\aaaa_aa.aaa
dirname =
tmp sane = \\aaaa.aaa\aaaaaaaa\aaaaaaaaa\aaaa\aaaa\aaaaa\aaaaaaa\aaaaaaa\aaaa.aaaaaaaa_aaaaaa\aa\aaaaa\aaaaaa\aaa\aaaaaa\aa\aaaaa\aaaaaaa_aaaaaaaaa_aaa

有什么想法为什么“tmp sane”有效而简单的目录名无效吗?我找不到与 Windows 网络名称/反斜杠相关的任何内容。

最佳答案

您很可能没有在 Windows 上运行此程序。该行为与在除实际 Windows 环境之外的任何环境中使用 os.path 模块完全一致。

os.path 调整行为以匹配当前平台。在 Windows 上,支持正斜杠和反斜杠,但在 Linux 和 Mac 上仅识别正斜杠。这是为了匹配您运行代码的平台上使用的实际约定。

如果您想在 POSIX 操作系统(如 Mac OS X 或 Linux)上从 Windows 路径中分离目录名,则需要导入 ntpath 模块;该模块是 Windows 上真正使用的模块,但它在其他平台上仍然可用:

import ntpath
result = ntpath.dirname(path)

查看顶部os.path module documentation :

Note: Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:

  • posixpath for UNIX-style paths
  • ntpath for Windows paths
  • macpath for old-style MacOS paths
  • os2emxpath for OS/2 EMX paths

在这种情况下,Cygwin 被视为 POSIX 环境,而不是 Windows。

关于python os.path.dirname 使用 Windows 网络路径产生错误的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27023115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com