Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.basename works with URLs, why?

Tags:

python

url

path

>>> os.path.basename('http://example.com/file.txt')
'file.txt'

.. and I thought os.path.* work only on local paths and not URLs? Note that the above example was run on Windows too .. with similar result.

like image 614
Sridhar Ratnakumar Avatar asked Jul 11 '09 00:07

Sridhar Ratnakumar


People also ask

What is the purpose of path basename () method?

The path. basename() method returns the filename part of a file path.

What is a basename path?

General description. 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 “/”.

Why do we use os path join?

Using os. path. join makes it obvious to other people reading your code that you are working with filepaths. People can quickly scan through the code and discover it's a filepath intrinsically.

What does os path do in Python?

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.


2 Answers

In practice many functions of os.path are just string manipulation functions (which just happen to be especially handy for path manipulation) -- and since that's innocuous and occasionally handy, while formally speaking "incorrect", I doubt this will change anytime soon -- for more details, use the following simple one-liner at a shell/command prompt:

$ python -c"import sys; import StringIO; x = StringIO.StringIO(); sys.stdout = x; import this; sys.stdout = sys.__stdout__; print x.getvalue().splitlines()[10][9:]"

Or, for Python 3:

$ python -c"import sys; import io; x = io.StringIO(); sys.stdout = x; import this; sys.stdout = sys.__stdout__; print(x.getvalue().splitlines()[10][9:])"
like image 75
Alex Martelli Avatar answered Oct 07 '22 19:10

Alex Martelli


On windows, look at the source code: C:\Python25\Lib\ntpath.py

def basename(p):
    """Returns the final component of a pathname"""
    return split(p)[1]

os.path.split (in the same file) just split "\" (and sth. else)

like image 34
sunqiang Avatar answered Oct 07 '22 19:10

sunqiang