Joining: string and absolute path with os.path

Why is this not working, what am I doing wrong?

>>> p1 = r'\foo\bar.txt'
>>> os.path.join('foo1', 'foo2', os.path.normpath(p1))
'\\foo\\bar.txt'

I was expecting this:

'foo1\\foo2\\foo\\bar.txt'

Edit:

Decision

>>> p1 = r'\foo\bar.txt'
>>> p1 = p1.strip('\\') # Strip '\\' so the path would not be absolute 
>>> os.path.join('foo1', 'foo2', os.path.normpath(p1))
'foo1\\foo2\\foo\\bar.txt'
+5
source share
3 answers

When he os.path.joinmeets the absolute path, he discards what he has accumulated to the end. An absolute line is a line starting with a slash (ans on windows with an additional drive letter). normpathwill not touch this slash, because it has the same concept of absolute paths. You must remove this slash.

And if I can ask: where did it come from in the first place?

+8
source

p1 is the absolute path (starts with \) - so it comes back on its own in the documentation:

join(a, *p)
    Join two or more pathname components, inserting "\" as needed.
    If any component is an absolute path, all previous path components
    will be discarded.
+4

, os.path.join , :

import os
p1 = os.path.join(os.sep, 'foo1', 'foo2')
p2 = os.path.join(os.sep, 'foo', 'bar.txt')

os.path.join(p1, p2.lstrip(os.sep))

If you want to change the paths, you can also do cool things like using lists:

# Make sure all folder names are lowercase:
os.path.join(p1, *[x.lower() for x in p2.split(os.sep)])
+2
source

All Articles