Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing networked file locations with pathlib

Tags:

python

pathlib

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.

like image 995
Alex Avatar asked May 08 '19 15:05

Alex


4 Answers

If you create your path as:

path = Path('//server-01/directory/filename.txt')

instead of comma separating each directory it will work.

like image 191
mikejham Avatar answered Oct 21 '22 14:10

mikejham


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

like image 43
HudsonMC Avatar answered Oct 21 '22 14:10

HudsonMC


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 '/'.

like image 2
keliu Avatar answered Oct 21 '22 13:10

keliu


Instantiating path as a PureWindowsPath should do the trick:

path = PureWindowsPath("//server-01", "directory", "file") # '\\\\server-01\\directory\\file'
like image 1
isaactfa Avatar answered Oct 21 '22 15:10

isaactfa