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)
well to open My pc (for windows) try:
import subprocess
subprocess.Popen('explorer ""')
"#if subprocess.Popen('explorer "{0}".format(full_path)') is struck at pc\my documents.
where full_path=os.path.join("your/path")"
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.
Following should do the job.
import subprocess
subprocess.Popen('explorer "{0}"'.format(full_folder_path))
Update -
Tested on my system -
full_path = os.path.join("P:/Project_Data/Projects_2013/",fldrname)
print full_path # Verify that it is correct
subprocess.Popen('explorer "{0}"'.format(full_path))
Related
Hi I cannot open files in python 3 actually I have a problem with the path. I don't know how to write the path for it.:/ For example I have a file(bazi.py) in folder(w8) in driver(F). How should i write it's path. Please help me im an amateur:/
In Windows, there are a couple additional ways of referencing a file. That is because natively, Windows file path employs the backslash "" instead of the slash. Python allows using both in a Windows system, but there are a couple of pitfalls to watch out for. To sum them up:
Python lets you use OS-X/Linux style slashes "/" even in Windows. Therefore, you can refer to the file as 'C:/Users/narae/Desktop/alice.txt'. RECOMMENDED.
If using backslash, because it is a special character in Python, you must remember to escape every instance: 'C:\Users\narae\Desktop\alice.txt'
Alternatively, you can prefix the entire file name string with the rawstring marker "r": r'C:\Users\narae\Desktop\alice.txt'. That way, everything in the string is interpreted as a literal character, and you don't have to escape every backslash.
File Name Shortcuts and CWD (Current Working Directory)
So, using the full directory path and file name always works; you should be using this method. However, you might have seen files called by their name only, e.g., 'alice.txt' in Python. How is it done?
The concept of Current Working Directory (CWD) is crucial here. You can think of it as the folder your Python is operating inside at the moment. So far we have been using the absolute path, which begins from the topmost directory. But if your file reference does not start from the top (e.g., 'alice.txt', 'ling1330/alice.txt'), Python assumes that it starts in the CWD (a "relative path").
using the os.path.abspath function will translate the path to a version appropriate for the operating system.
os.path.abspath(r'F:\w8\bazi.py')
I've been working on a program that reads out an specific PDF and converts the data to an Excel file. The program itself already works, but while trying to refine some aspects I ran into a problem. What happens is the modules I'm working with read directories with simple slashes dividing each folder, such as:
"C:/Users/UserX"
While windows directories are divided by backslashes, such as:
"C:\Users\UserX"
I thought using a simple replace would work just fine:
directory.replace("\" ,"/")
But whenever I try to run the program, the \ isn't identified as a string. Instead it pops up as orange in the IDE I'm working with (PyCharm). Is there anyway to remediate this? Or maybe another useful solution?
In general you should work with the os.path package here.
os.getcwd() gives you the current directory, you can add a subfolder of it via more arguments, and put the filename last.
import os
path_to_file = os.path.join(os.getcwd(), "childFolder", filename)
In Python, the '\' character is represented by '\\':
directory.replace("\\" ,"/")
Just try adding another backslash.
First of all you need to pass "C:\Users\UserX" as a raw string. Use
directory=r"C:\Users\UserX"
Secondly, suppress the backslash using a second backslash.
directory.replace("\\" ,"/")
All of this is required as in python the backslash (\) is a special character known as an escape character.
Try this:
import os
path = "C:\\temp\myFolder\example\\"
newPath = path.replace(os.sep, '/')
print(newPath)
Output:<< C:/temp/myFolder/example/ >>
I have a problem when programming in Python running under Windows. I need to work with file paths, that are longer than 256 or whatsathelimit characters.
Now, I've read basically about two solutions:
Use GetShortPathName from kernel32.dll and access the file in this way.
That is nice, but I cannot use it, since I need to use the paths in a way
shutil.rmtree(short_path)
where the short_path is a really short path (something like D:\tools\Eclipse) and the long paths appear in the directory itself (damn Eclipse plugins).
Prepend "\\\\?\\" to the path
I haven't managed to make this work in any way. The attempt to do anything this way always result in error WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: <path here>
So my question is: How do I make the 2nd option work? I stress that I need to use it the same way as in the example in option #1.
OR
Is there any other way?
EDIT: I need the solution to work in Python 2.7
EDIT2: The question Python long filename support broken in Windows does give the answer with the 'magic prefix' and I stated that I know it in this question. The thing I do not know is HOW do I use it. I've tried to prepend that to the path but it just failed, as I've written above.
Well it seems that, as always, I've found the answer to what's been bugging me for a week twenty minutes after I seriously ask somebody about it.
So I've found that I need to make sure two things are done correctly:
The path can contain only backslashes, no forward slashes.
If I want to do something like list a directory, I need to end the path with a backslash, otherwise Python will append /*.* to it, which is a forward slash, which is bad.
Hope at least someone will find this useful.
Let me just simplify this for anyone looking for a straight answer:
For python < 3: Path needs to be unicode, prepend string with u like u'C:\\path\\to\\file'
Path needs to start with \\\\?\\ (which is escaped into \\?\) like u'\\\\?\\C:\\path\\to\\file'
No forward slashes only backslashes: / --> \\
It has to be an absolute path; it does not work for relative paths
py 3.8.2
# Fix long path access:
import ntpath
ntpath.realpath = ntpath.abspath
# Fix long path access.
In my case, this solved the problem of running a script from a long path.
(https://developers.google.com/drive/api/v3/quickstart/python)
But this is not a universal fix.
It looks like the ntpath.realpath implementation has problems. This code replaced it with a dummy.
it works for me
import os
str1=r"C:\Users\manual\demodfadsfljdskfjslkdsjfklaj\inner-2djfklsdfjsdklfj\inner3fadsfksdfjdklsfjksdgjl\inner4dfhasdjfhsdjfskfklsjdkjfleioreirueewdsfksdmv\anotherInnerfolder4aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\5qbbbbbbbbbbbccccccccccccccccccccccccsssssssssssssssss\tmp.txt"
print(len(str1)) #346
path = os.path.abspath(str1)
if path.startswith(u"\\\\"):
path=u"\\\\?\\UNC\\"+path[2:]
else:
path=u"\\\\?\\"+path
with open(path,"r+") as f:
print(f.readline())
if you get a long path(more then 258 char) issue in windows then try this .
I am complete newbie in Python and have to modify existing Python script. The script copies file to other path like following:
err=shutil.copyfile(src, dst)
This works unless dst contains character like &:
dst = "Y:\R&D\myfile.txt"
In this case I get windows error popup that says
Open file or Read file error
Y:\R
I tried to escape & using back slash, double back slash and wrapping the string with additional quotes: dst = "\"Y:\R&D\myfile.txt\"".
Nothing works in last case I get "invalid path" error message from shutil.
How can I solve this problem?
I doubt that ampersand is supported on most platforms. You will likely have to make a call to a windows specific program. I suggest robocopy since its really good at copying files. If it's not included in your version of windows, you can find it in the windows server administrator toolkit for 2003.
It works for me if I change all the \ in the filepaths to / (in both src and dst strings). Yes, I know you're using Windows, but filepaths always seem to be less fussy in Python if you use /, even in Windows.
Also, it looks like you're copying to a network drive. Do you get the same problem copying to c:\R&D\?
What flavor of Windows are you using? shutil.copyfile() works fine for me with & in directory names, in both src and dst paths, in both local and network drives on XP -- as long as I use / in place of \.
Easiest solution, signify to python that the string is raw and not to escape it or modify it in any way:
import shutil
src = r"c:\r&d\file.txt"
dst = r"c:\r&d\file2.txt"
err=shutil.copyfile(src, dst)
Try to escape the "\" with "\ \", this command must work (for example):
shutil.copyfile("Y:\\R&D\\myfile.txt", "C:\\TMP")
Here are few ways to make it work on windows:
Approach 1: (already explained)
import shutil; shutil.copy(src,dest)
as long as src/dest are using r'c:\r&d\file' string format. It also works with forward "/" slashes as well.
Approach 2: Notice use of double quotes instead of single quotes on windows.
src = r'c:\r & d\src_file'
os.system('copy "{}" "{}"'.format(src,dest))
1 file(s) copied
Last resort:
with open(dest, 'wb') as f:
f.write(open(src,'rb').read())
Unlike os.system, this preferred implementation subprocess.call could not work with any quoting approach on windows. I always get The specified path is invalid. Did not try on unix.
I have a wxPython application. I am taking in a directory path from a textbox using GetValue().
I notice that while trying to write this string to a variable:
"C:\Documents and Settings\tchan\Desktop\InputFile.xls",
python sees the string as
'C:\\Documents and Settings\tchan\\Desktop\\InputFile.xls' (missing a slash between "Settings" and "UserName).
More info:
The directory path string is created by the "open file" dialog, which creates a standard 'choose file' dialog you see in any 'open' function in a text processor. The string is written to a textbox and read later when the main thread begins (in case the user wants to change it).
EDIT: I realise that the problem comes from the '\t' being seen as a "tab" instead of normal forward slash. However I don't know how to work past this, since
I suspect there's a different way to get that path from wx that would avoid this issue, since it seems like this would be a fairly common problem. That said, there are a few ways to fix a mangled path like you describe, by converting the string you have to a raw string.
rawpath = "%r" % path
The resulting rawpath will likely be somewhat messy since it will probably add extra escapes to the backslashes and give you something like:
"'C:\\\\Documents and Settings\\tchan\\\\Desktop\\\\InputFile.xls'"
It seems like os.path.normpath will clean that up though.
import os.path
os.path.normpath(rawpath)
not saying this is the correct solution, but you can
x = "C:\tmp".encode('string-escape')
x
'C:\\tmp'
better, if you are using the file dialog
os.path.join(dlg.GetDirectory(),dlg.GetFilename())
where dlg is your dialog
You have to escape the slashes. \\ will store a literal \ in the string:
path = "C:\\Documents and Settings\\tchan\\Desktop\\InputFile.xls"