3

I'm trying to open shared folder using python(Windows 10)

this is the location that I try to get access : \\192.168.1.4\aaaa\form.txt If I code like f= open("\\192.168.1.4\aaaa\form.txt",'w') simple full code:

f=open("\\192.168.1.4\aaaa\form.txt",'w')
f.write("hihi test is it works?")
f.close()

It doesn't work because the letter '\'

So how can I access the file shared folder?

Dirk Horsten
  • 3,753
  • 4
  • 20
  • 37
Jeongmin
  • 57
  • 2
  • 8
  • 1
    read about escape chars, you need \\\\, but actually better import os and use os.path module – Drako May 31 '18 at 05:39

1 Answers1

8

When using Windows paths, always use raw string literals, or you'll get weirdness (e.g. \f becomes the form-feed character, \a becomes the alert/bell character).

Instead of open("\\192.168.1.4\aaaa\form.txt",'w'), do open(r"\\192.168.1.4\aaaa\form.txt",'w') (note the r preceding the open quote on the path). This makes the backslashes only escape the quote character itself (and otherwise behave as normal characters, not escapes), avoiding interpretation of random characters as ASCII escapes.

Also, as a best practice, use with statements to avoid the need to (and possibility of forgetting or bypassing) call close:

with open(r"\\192.168.1.4\aaaa\form.txt",'w') as f:
    f.write("hihi test is it works?")
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271