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?
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 “/”.
path. basename() method in Python is used to get the base name in specified path.
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.
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 pathsntpath
for Windows paths
os.sep
) is backslash (\
). Slash is also accepted (Windows OS functions accept it)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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With