python - 在 Windows 路径上使用 os.path.dirname

标签 python linux python-2.7

我使用的是运行 python 2.7 的 Linux 机器。 我想使用os.path.dirname()获取文件完整路径的父目录(不是来自 native ),例如:
C:\\documents and settings\\Dan\\yada\\1.txt =>
将导致C:\\documents and settings\\Dan\\yada

但令人惊讶的是,我得到的是空字符串。

谁能解释一下原因以及如何解决?

最佳答案

改用ntpath:

>>> import ntpath
>>> ntpath.dirname('C:\\documents and settings\\Dan\\yada\\1.txt')
'C:\\documents and settings\\Dan\\yada'

来自the documentation :

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

关于python - 在 Windows 路径上使用 os.path.dirname,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402879/

相关文章:

python - 在 Python 中存储带前导零的整数

python - python异常情况下的变量范围

python - 获取 'NameError: name ' <我的函数 >' is not defined' 错误

java - 如何使用 python 使用 Selenium WebDriver 处理身份验证弹出窗口?

python - ValueError : base_distribution needs to have shape with size at least 6, 但得到了 torch.Size([6])

python - 使用多个命令运行子进程并分离到后台保持顺序

linux - Linux 中多个系统调用的原因

Python:拦截一个类加载 Action

python - Pandas 将表写入 MySQL : "unable to rollback"

linux - 为什么UDP数据包是从默认接口(interface)地址发送的,而不是从接收客户端数据包的地址发送的?