I'm trying to test a program using Python's pathlib
module. With the os
module, you used to be able to access networked drives by just following the same url-like form. But for some reason, you can't do this with pathlib
. Or at least I can't figure out how to do it.
With the os
module, all one would have to do is:
path = os.path.join(r'//server-01', 'directory', 'filename.txt')
But if you try to do this with the pathlib
module, one could try something like:
path = Path('//server-01', 'directory', 'filename.txt')
If I'm on a Windows machine, path will resolve to:
>> WindowsPath('/server-01/directory/filename.txt)
And if I were to say path.exists()
I will of course get False
. Because yes, /server-01
does NOT exist, however //server-01
does exist.
Ideally of course, the result I expect to get when I run path.exists()
is True
and if I were to display path
it would look something like:
>> WindowsPath('//server-01/directory/filename.txt')
Update
It's kind of hacky, but it works I guess, regardless I'd like to know the right way to do it.
In order to get to the network location you can:
os.chdir(join(r'//server-01', 'directory', 'filename.txt'))
path = Path()
path = path.resolve()
The result is something like:
>> WindowsPath('//server-01/directory/filename.txt')
path.exists()
>> True
If anyone knows the better way to do it, let me know.
If you create your path as:
path = Path('//server-01/directory/filename.txt')
instead of comma separating each directory it will work.
The server name by itself is not a valid component of a UNC path. You must also include a share. So path = Path('//server-01/directory', 'file')
will work. It should resolve
and return True
when you run path.exists()
.
Microsoft docs here: https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dfsc/149a3039-98ce-491a-9268-2f5ddef08192
after several attempts, I think you can visit the smb folder/file with pathlib
by:
folder = pathlib.Path('//server/')
file = pathlib.Path('//server/') / 'relative/path/to/file'
# or
file = pathlib.Path('//server/relative/path/to/file')
the key is that if you want to visit a smb folder, the arg should end with '/'.
Instantiating path
as a PureWindowsPath
should do the trick:
path = PureWindowsPath("//server-01", "directory", "file") # '\\\\server-01\\directory\\file'
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