4

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?

1
  • 1
    read about escape chars, you need \\\\, but actually better import os and use os.path module Commented May 31, 2018 at 5:39

1 Answer 1

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?")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.