Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing shared folder in windows using python

Tags:

python

windows

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?

like image 554
Jeongmin Avatar asked Oct 19 '25 14:10

Jeongmin


1 Answers

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?")
like image 116
ShadowRanger Avatar answered Oct 21 '25 02:10

ShadowRanger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!