73

I have a file that I would like to copy from a shared folder which is in a shared folder on a different system, but on the same network. How can I access the folder/file? The usual open() method does not seem to work?

BrickByBrick
  • 1,111
  • 2
  • 9
  • 12

3 Answers3

107

Use forward slashes to specify the UNC Path:

open('//HOST/share/path/to/file')

(if your Python client code is also running under Windows)

DavidJ
  • 3,990
  • 4
  • 24
  • 40
johnsyweb
  • 129,524
  • 23
  • 177
  • 239
  • 2
    This just solved a problem that was annoying me, thanks! – Meelah Feb 01 '16 at 15:01
  • 3
    This only works on Windows (yes, the question is tagged Windows, but accessing a Windows server from non-Windows OS may also be tagged as such). Anyone care to add a solution for other platforms (e.g. Linux) - if possible without something like Samba? – DavidJ Jul 18 '16 at 18:57
  • 4
    @DavidJ If you're using SMB on Linux, I'd expect `//HOST/share/` to be mounted (somewhere like `/mnt/share`) and the file to be opened like a regular file (`open('/mnt/share/path/to/file')`). – johnsyweb Jul 19 '16 at 12:11
  • DavidJ Did you try @Johnsyweb solution? Did it work? – Azy Sır Feb 12 '19 at 06:11
  • @Johnsyweb have you got another solution for this somewhere? Possibly github so I can view and re-use? I'm on a MAC trying to hit a shared network address. It is mounted - I have followed all solutions on this place all are giving FileNotFoundError: [Errno 2] No such file or directory: – Azy Sır Feb 12 '19 at 06:17
  • @AzySır I'm afraid I do not. I would expect `//HOST/share/` to be mounted (somewhere like `/Volumes/share`) and the file to be opened like a regular file (`open('/Volumes/share/path/to/file')`). – johnsyweb Feb 12 '19 at 10:16
  • @Johnsyweb my issue is im on OSX trying to open up a WINDOWS Network Server. It's saying not found even though it is evidently mounted - not sure how to proceed on it – Azy Sır Feb 13 '19 at 00:35
  • if you are on MacOS, and you've mounted your server via Go > Connect to Server, you should be able to see your server if you use os.listdir("/Volumes/") – yl_low Jun 29 '20 at 11:02
  • @AzySır I'm having a similar issue. Did you ever find a solution? – user3574939 Dec 02 '20 at 18:54
39

How did you try it? Maybe you are working with \ and omit proper escaping.

Instead of

open('\\HOST\share\path\to\file')

use either Johnsyweb's solution with the /s, or try one of

open(r'\\HOST\share\path\to\file')

or

open('\\\\HOST\\share\\path\\to\\file')

.

glglgl
  • 85,390
  • 12
  • 140
  • 213
6

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

Andrew Peters
  • 103
  • 1
  • 5