Os.path : can you explain this behavior?

I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.

I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :

filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')


It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".

Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.

Asked by: Adelaide847 | Posted: 28-01-2022

Answer 1

If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)

>>> import ntpath
>>> filepath = r"c:\ttemp\FILEPA~1.EXE"
>>> print ntpath.basename(filepath)
>>> print ntpath.splitdrive(filepath)
('c:', '\\ttemp\\FILEPA~1.EXE')

Answered by: Julian953 | Posted: 01-03-2022

Answer 2

From a os.path documentation:

Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.

If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string.

If you want to solve windows paths on any platform, you can just use a simple regexp:

import re
(drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups() 

drive will be a drive letter followed by : (eg. c:, u:) or None, and tail the whole rest :)

Answered by: Dainton809 | Posted: 01-03-2022

Answer 3

See the documentation here, specifically:

splitdrive(p) Split a pathname into drive and path. On Posix, drive is always empty.

So this won't work on a Linux box.

Answered by: Daryl720 | Posted: 01-03-2022

Similar questions

Python behavior of string in loop

In trying to capitalize a string at separators I encountered behavior I do not understand. Can someone please explain why the string s in reverted during the loop? Thanks. s = 'these-three_words' seperators = ('-','_') for sep in seperators: s = sep.join([i.capitalize() for i in s.split(sep)]) print s print s stdout: These-Three_words These-three_Words These-three_Words

string - Python : Revert to base __str__ behavior

How can I revert back to the default function that python uses if there is no __str__ method? class A : def __str__(self) : return "Something useless" class B(A) : def __str__(self) : return some_magic_base_function(self)

python - Weird lxml behavior

Consider the following snippet: import lxml.html html = '<div><br />Hello text</div>' doc = lxml.html.fromstring(html) text = doc.xpath('//text()')[0] print lxml.html.tostring(text.getparent()) #prints <br>Hello text I was expecting to see '<div><br />Hello text</div>', because br can't have nested text and is "self-close...

Strange behavior with python import

So I am trying to import a module "foo" that contains directories "bar" and "wiz". "bar" contains python files a.py, b.py, and c.py. "wiz" contains python files x.py, y.py and z.py. $ ls foo __init__.py bar wiz $ ls foo/bar __init__.py a.py b.py c.py $ ls foo/wiz __init__.py x.py y.py z.py In the python shell (more precisely, the django manage.py she...

python - Django ORM's "related data" loading behavior

In LINQ (I come from a C# background), you can manually load data for related tables via the Include("xxx") method from a in ctx.MainTable.Include("SubTable") select a; In the above code, every instance of MainTable is loaded and all the data for MainTable.SubTable is also loaded. If "Include" is not called, every returned MainTable's SubTable property will return null. Are there ...

python - Weird Cron ls Behavior

I have a Python script that is running a few ls commands. This script runs under cron all day. I use awk to write out the column that the filename is in when ls -l is executed. When I run the script via command line the output looks like this -rw-rw---- 1 mysql adm 141 2010-03-25 08:56 mysql-bin.000485 -rw-rw---- 1 mysql adm 141 2010-03-25 09:01 mysql-bin.000486 -rw-rw---- 1 mysql adm ...

python - Why does the "is" keyword have a different behavior when there is a dot in the string?

Consider this code: >>> x = "google" >>> x is "google" True >>> x = "google.com" >>> x is "google.com" False >>> Why is it like that? To make sure the above is correct, I have just tested on Python 2.5.4, 2.6.5, 2.7b2, Python 3.1 on windows and Python 2.7b1 on Linux. It looks like there is consistency across all of them, so it's ...

python - unusual django admin behavior when storing string values

Using django trunk r13359 and django piston, I created a small restful service that stores string values. This is the model I am using to store strings: class DataStore(models.Model): data = models.CharField(max_length=200) url = models.URLField(default = '', verify_exists=False, blank = True) I used curl to post following data: curl -d "data=somedata" http...

python - list(y) behavior is "wrong" on first call

I have an iterator with a __len__ method defined. Questions: If you call list(y) and y has a __len__ method defined, then __len__ is called.    1) Why? In my output, you will see that the len(list(y)) is 0 on the first try. If you look at the list output, you will see that on the first call, I receive an empty list, and on the second call I receive...

python - Django 1.2 : strange logging behavior

I have a really strange problem with the standard logging module used in django views. Sometimes it works perfectly and sometimes it does not log messages. Here is the structure of my code : /mysite/ (Django root) my_logging.py (logging configuration) settings.py views.py (global views) data_objects.py (objects only containing data, similar to POJO) uploader/ (application) ...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python