Extracting directory path from full file path without the file name

Viewed 396

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. 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'

I have searched through stack but couldn't find any answer that works for me.

1 Answers

You can use os.path.split(). According to the documentation, it splits the path based on the operating system python is running on

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

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:

>>> 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')
Related