jon141 jon141 - 3 months ago 18
Python Question

Open windows explorer at a specific network location in Python

I have tried so many variants of a theme to get this explorer window open at the P:\ drive, from what my little knowledge tells me, the fact the path to the folder is anywhere but the C:\ drive means it fails (it works with C:) so perhaps the path is wrong? the code below shows some of the tries i have made but still no luck, "P:" is mapped the same on all machines.

def Open_Win_Explorer_and_Select_Dir():
import subprocess
fldrname = os.path.basename(currentproject.get())
print(fldrname)
#subprocess.Popen('c:\windows\EXPLORER.EXE', cwd=(P:/Projects 2013/)
#subbprocess.Popen('c:\\windows\\EXPLORER.EXE' cwd=('P:\\Projects_2013\\')fldrname)
#subprocess.Popen(r'C:/Windows/explorer.exe', cwd=r'//WRDBSVR/Project_Data/Projects_2013/'+fldrname)
subprocess.Popen('explorer /n, /select r"\\192.168.0.27\\Project_Data\\Projects_2013\\"'+fldrname)
#subprocess.Popen('explorer /n, /select r"P:\\Project_Data\\Projects_2013\\"'+fldrname)

Answer

Appart from the fact that Ashish Nitin Patil's answer is definitly better, as using a variable for paths is always a good idea, you have a problem with your quotes:

# This line is not correct
'explorer /n, /select r"\\192.168.0.27\\Project_Data\\Projects_2013\\"'+fldrname
#                      ^you start a new string without ending previous one
# this one is correct
'explorer /n, /select ' + r'\192.168.0.27\Project_Data\Projects_2013\' + fldrname
#                     ^first ending string start

Besides, using raw strings (r"xxx") means that \ will not escape characters, so you shall not double them. If you want to double them, you do not need prepend r.

Last remark: take care to avoid string concatenation (+) when working with paths; you should use os.path.join() instead.