简体   繁体   English

从没有文件名的完整文件路径中提取目录路径

[英]Extracting directory path from full file path without the file name

I have a function that receives full file path as a string and the goal is to return just the file path without the filename.我有一个 function 接收完整的文件路径作为字符串,目标是只返回没有文件名的文件路径。 The goal also is to handle all file type such as Windows, Unix etc. I had to replace \ with / which works fine for Windows file paths but seems unnecessary for Unix paths. The goal also is to handle all file type such as Windows, Unix etc. I had to replace \ with / which works fine for Windows file paths but seems unnecessary for Unix paths.

def get_path(file):
    file = file.replace('\\', '/')
    path = os.path.dirname(file)
    return path

Is there any way to extract the path without replacing the backward slash?有没有办法在不替换反斜杠的情况下提取路径? Here's are two example input path strings这是两个示例输入路径字符串

Windows: 'c:\\Program Files\\user\\file1.txt' Unix: 'file/path/name.txt' Windows: 'c:\\Program Files\\user\\file1.txt' Unix: 'file/path/name.txt'

I have searched through stack but couldn't find any answer that works for me.我已经搜索了堆栈,但找不到任何适合我的答案。

You can use os.path.split() .您可以使用os.path.split() According to the documentation , it splits the path based on the operating system python is running on根据文档,它根据运行python的操作系统拆分路径

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. os.path 模块始终是适用于 Python 正在运行的操作系统的路径模块,因此可用于本地路径。 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它们都具有相同的接口:用于 UNIX 样式路径的 posixpath

  • ntpath for Windows paths Windows 路径的 ntpath
  • macpath for old-style MacOS paths macpath 用于旧式 MacOS 路径
  • os2emxpath for OS/2 EMX paths os2emxpath 用于 OS/2 EMX 路径

What if you have windows path and you're running on Ubuntu/Linux, then you can use ntpath as said in the documentation just like so:如果您有 windows 路径并且您在 Ubuntu/Linux 上运行,那么您可以使用文档中所述的ntpath ,如下所示:

>>> import ntpath

>>> ntpath.split("c:\\Program Files\\user\\file1.txt")
('c:\\Program Files\\user', 'file1.txt')

>>> ntpath.split("file/path/name.txt")
('file/path', 'name.txt')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM