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

标签 python string windows dirname

我有这个代码片段

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/

相关文章:

c - 如何克服 Visual Studio 的堆栈大小问题(使用大数组运行 C 代码)

php - 如何在 Windows 上为 PHP 安装 PDO 驱动程序?

python - 无法在 hvplot 轴上绘制 datetime64[ns] ('pandas_datetime_types' 未定义'错误)

python - Pandas 分组; if 条件 : sum else: max for given column based on another column

python - mpi4py:动态数据处理

c++ - 在 C/C++(ms) 中将 char[] 转换为 tchar[] 的最简单方法是什么?

c - C语言中如何将一个字符串分成3部分

python - 如何将枚举名称用作其他信息的值

python - 如何将python Unicode字符串转换为字节

linux - 对 AIX 和批处理文件的理解和澄清