Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get basename of a Windows path in Linux

Assume I have a string that hold a Windows file address, let's say

local_address = "C:\\TEMP\\filename.txt"

to retrieve the filename from the address above I use

import os
filename = os.path.basename(local_address)    

In Windows, when I run the code the output is

>>> print filename
filename.txt

But when running the code in linux I get

>>> print filename
C:\TEMP\filename.txt

The reason is (what I think is) that when the Linux implementation of Python expects Linux local file address formats and has no idea about Windows addresses. Letting manual parsing of the address alone, are there other solutions so that I get uniform results?

like image 261
Ahmad Siavashi Avatar asked Jan 15 '17 09:01

Ahmad Siavashi


People also ask

What is the basename of a path?

The basename() function takes the pathname pointed to by path and returns a pointer to the final component of the pathname, deleting any trailing '/' characters. If the string consists entirely of the '/' character, basename() returns a pointer to the string “/”.

What does os path basename do?

path. basename() method in Python is used to get the base name in specified path.

How do I get the base of a directory in Python?

dirname() method in Python is used to get the directory name from the specified path. Parameter: path: A path-like object representing a file system path. Return Type: This method returns a string value which represents the directory name from the specified path.


2 Answers

Python have multiple implementations of os.path module, and if you're lucky, your python may be equipped with ntpath module:

>>> import ntpath
>>> ntpath.basename(r'C:\TEMP\filename.txt')
'filename.txt'

According to os.path 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
like image 125
myaut Avatar answered Oct 10 '22 03:10

myaut


  • On windows, the file separator (os.sep) is backslash (\). Slash is also accepted (Windows OS functions accept it)
  • On Linux, the file separator (os.sep) is slash (/). Backslash is not accepted.

what would work would be os.path.basename(local_address.replace('\\',os.sep))

to turn the backslashes into slashes so basename can process it (and it would also work on windows: you'd replace something by the same thing)

like image 28
Jean-François Fabre Avatar answered Oct 10 '22 03:10

Jean-François Fabre