我使用的是运行 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'
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 pathsntpath
for Windows pathsmacpath
for old-style MacOS pathsos2emxpath
for OS/2 EMX paths
关于python - 在 Windows 路径上使用 os.path.dirname,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402879/