Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.path.join not working properly for network paths

Tags:

python

Any ideas why this will not join properly in Python 2.6 Win?

import os

myPath = "\\\\192.168.1.50\\Shared"
myPath2 = "\\Folder2"
myFile = "1.txt"

print os.path.join(myPath, myPath2, myFile)

Result:

\Folder2\1.txt

I was expecting the result to be "\\192.168.1.50\Shared\Folder2\1.txt" !

like image 720
Andriusa Avatar asked Feb 28 '26 21:02

Andriusa


2 Answers

Join is a convenience function, it is not too intelligent. For example, it does not verify existence of paths, etc. It just follows some formal rules.

As of your question, remove extra slash in myPath2 definition.

import os

myPath = "\\\\192.168.1.50\\Shared"
myPath2 = "Folder2"
myFile = "1.txt"

print os.path.join(myPath, myPath2, myFile)

gives \\192.168.1.50\Shared\Folder2\1.txt

You will have same problem with ordinary paths:

import os

myPath = "C:\\Shared"
myPath2 = "\\Folder2"
myFile = "1.txt"

print os.path.join(myPath, myPath2, myFile)

gives \Folder2\1.txt

like image 155
Yevgen Yampolskiy Avatar answered Mar 02 '26 11:03

Yevgen Yampolskiy


If any component is an absolute path, all previous components (on Windows, including the previous drive letter, if there was one) are thrown away, and joining continues.

I need to remove the slashes from the beginning of myPath2, otherwise it will be treeted as absolute path and myPath will be ignored!

import os

myPath = "\\\\192.168.1.50\\Shared"
myPath2 = "Folder2"
myFile = "1.txt"

print os.path.join(myPath, myPath2, myFile)

Result:

\\192.168.1.50\Shared\Folder2\1.txt
like image 21
Andriusa Avatar answered Mar 02 '26 10:03

Andriusa