Add an extra \ in python winpaths - python

Using python with windows I'm trying to get my program to see if Dropbox.exe exists if it doesn't nothing will happen if it does then the program will run. I used the print appdata as a debugging feature and this is what it prints: C:\Users\Me\AppData\Roaming
and I think the problem is that it needs to print C:\\Users\\me\\AppData\\Roaming\\ so then I can add the last part as \\Dropbox\\bin\\Dropbox.exe
import winpaths
appdata = winpaths.get_appdata()
print appdata
try:
with open('appdata\Dropbox\bin\Dropbox.exe') as f: pass
except IOError as e:
print 'dropbox cant be found'

First of all, you should use forward slashes for paths as backslashes are used to escape special characters, and forward slashes will work fine, even under windows. Alternatively, use raw strings (r"C:\some\path"). For an example of why you should do this:
>>> print("\path\to\random")
andom o
>>> print("/path/to/random")
/path/to/random
>>> print(r"\path\to\random")
\path\to\random
To do what you want, look at os.path.join() to join the two parts:
>>> import os
>>> os.path.join("/path/to", "some/file")
'/path/to/some/file'
Note that I am using Linux, so this produces a linux-style path, however, under Windows it will adjust accordingly.
So in your case:
with open(os.path.join(appdata, 'Dropbox/bin/Dropbox.exe')) as f:
...

You're likely to encounter bugs due to backslashes escaping characters in your string. Use a raw string to prevent this:
with open(r'appdata\Dropbox\bin\Dropbox.exe') as f:
Also, to add extra bits to pathnames, look at the os.path module, especially os.path.join.

You don't seem to be using the appdata variable in your open:
with open(appdata + r'\Dropbox\bin\Dropbox.exe') as f: pa

Related

How to get my path written with back slashes instead of forward slashes?

I hope someone can help as I am stuck, I can't find the answer to this problem anywhere on google.
I need to replace my forward slash path with a backslash path in order for it to work with windows command prompt. Forward slash paths work for local folders, i.e. C:/Users/Lorcan - but not network folders, i.e. //Networkfolder/Storage
I learned that you can't use the backslash in python as it is a special character, so you must use two backslashes. However, this causes my path to have too many backslashes, and command prompt doesn't work.
>>> s = '//Networkfolder/Storage/Myfolder/Myfile'
>>> s2 = s.replace('/','\\')
>>> s2
'\\\\Networkfolder\\Storage\\Myfolder\\Myfile'
In the python shell, backslashes are displayed as \\, but it's really \ in the string. Your code is working fine, the real string is correct, it's being displayed like that.
You can print out your current working directory instead of writing it out:
import os
cwd = str(os.getcwd())
x = cwd.replace("/", "\\")
print(x)
This worked for me, hope it does for you as well!

How to handle \2 in the Windows path with Python?

I run an external function that returns a Windows path to a file on disk as a string (part of the string:
Error details are at "C:\Users\ADMINI~1\AppData\Local\Temp\2\BuildErrors.txt" Succeeded
So, I load the result returned into a string variable:
s = '''Error details are at "C:\Users\ADMINI~1\AppData\Local\Temp\2\BuildErrors.txt" Succeeded'''
file_path = s.split('"')[1]
print file_path
> C:\Users\ADMINI~1\AppData\Local\Temp\BuildErrors.txt #(with STX icon after Temp
If I access the file_path in the Python Shell, its printed like this:
file_path
'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\x02\\BuildErrors.txt'
I understand that \2 is handled as a special character in Python, but this makes it impossible to for me to read the file as the path is not valid.
As I am getting the string from external function, I already have a string object and as far as I know, you cannot make a raw string (r'') from that.
I've tried s.encode('string-escape') on the source string, but it keeps the \x02 in place.
How do produce a valid path by handling the \2 in it?
So you have a few things going on.
1) You should be using Python 3. Its time.
2) Monik's answer is correct if you just want to switch to unix style path separator characters. Python will let you use unix style paths on a windows system. Just remember that other windows shells and program will not.
3) Here is what is going on. If your string is in a file called fred.txt then
>>> with open('fred.txt') as f:
... derf = f.readline()
...
>>> derf
'Error details are at "C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\BuildErrors.txt" Succeeded'
>>> file_path = derf.split('"')[1]
>>> file_path
'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2\\BuildErrors.txt'
>>> os.path.split(file_path)
('C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\2', 'BuildErrors.txt')
>>>
Then everything seems to work ok. The python shell displays the double slashes because of how it stores strings internally. If you write that value to a file or print it to the screen you get
>>> print(file_path)
C:\Users\ADMINI~1\AppData\Local\Temp\2\BuildErrors.txt
>>>
So now we get to the crux of the problem. The slash character '\' has special meaning in python strings. It is used to tell the system, hey what follows might be different. So I can specify characters that don't appear on my keyboard via hexadecimal or unicode. for example 3 ways to define a pound sign in a string. I recommend reading http://python-reference.readthedocs.io/en/latest/docs/str/escapes.html
>>> a = "#"
>>> b = "\x23"
>>> c = "\u0023"
>>> a
'#'
>>> b
'#'
>>> c
'#'
>>> a == b
True
>>> a == c
True
>>> b == c
True
>>>
So if '\' has a special meaning, how do I tell the system that I really just want a slash? You escape it! '\\' in the python shell just says I want a slash.
>>> s = "\\"
>>> s
'\\'
>>> print(s)
\
>>>
If your string path is 'C:\ABC\xyz.txt'
then the statement, it gives you 'C:\\ABC\\xyz.txt'
To make it a valid path for python file handling, it should be in format of C:/ABC/xyz.txt
So if path = 'C:\\ABC\\xyz.txt'
path = path.replace("\\","/")
and path is in right format.

Resolving mixed slashes from sys.path and os.path.join

I need to resolve a disparity between the separator that sys.path is providing, and the separator that os.path.join is using.
I mimicked this Esri method (Techniques for sharing Python scripts) to make my script portable. It is being used in Windows for now, but will eventually live on a Linux server; I need to let Python determine the appropriate slash.
What they suggest:
# Get the pathname to this script
scriptPath = sys.path[0]
# Get the pathname to the ToolShare folder
toolSharePath = os.path.dirname(scriptPath)
# Now construct pathname to the ToolData folder
toolDataPath = os.path.join(toolSharePath, "ToolData")
print "ToolData folder: " + toolDataPath
But this outputs ToolData folder: C:/gis\ToolData -- and obviously the mixed slashes aren't going to work.
This Question (mixed slashes with os.path.join on windows) includes the basic approach to a solution:
check your external input (the input you apparently do not control the format of) before putting it in os.path.join. This way you make sure that os.path.join does not make bad decisions based on possibly bad input
However, I'm unsure how to ensure that it will work cross-platform. If I use .replace("/","\\") on the sys.path[0] result, that's great for Windows, but isn't that going to cause the same mixed-slash problem once I transition to Unix?
How about using os.path.normpath()?
>>> import os
>>> os.path.normpath(r'c:\my/path\to/something.py')
'c:\\my\\path\\to\\something.py'
Also worth mentioning: the Windows path API doesn't care whether forward or back slashes are used. Usually it's the fault of program that doesn't handle the slashing properly. For example, in python:
with open(r'c:/path/to/my/file.py') as f:
print f.read()
will work.
After reading the documentation and trying a lot of variations:
The os.path.abspath function can "clean" the slashes, so whichever direction slash sys.path[0] decides to use, the slashes will be replaced with the preferred separator.
scriptPath = sys.path[0]
toolDataPath = os.path.join(scriptPath, "ToolData")
Result: C:/gis\ToolData
scriptPath = sys.path[0]
toolSharePath = os.path.abspath(scriptPath)
# or, in one line: toolSharePath = os.path.abspath(sys.path[0])
toolDataPath = os.path.join(toolSharePath, "ToolData")
Result: C:\gis\ToolData
There is an os.sep character in Python, which stores your OS's preferred folder separating character. Perhaps you could perform a manual string join using that?
On Linux:
>>> import os
>>> os.sep
'/'
https://docs.python.org/2/library/os.html#os.sep

Error opening a csv file in python from a specific directory

I am very new to python and I am not having much experience in programming.
I try to open a CSV file from a specific directory and I get error.
import csv
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
Error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
ifile = open('F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb");
IOError: [Errno 22] invalid mode ('rb') or filename: 'F:\\Study\\CEN\\Mini Project\\Data Sets\test.csv'
What to do ????
Use forward slashes:
ifile = open('F:/Study/CEN/Mini Project/Data Sets/test.csv', "rb");
Or at least escape your backslashes:
ifile = open('F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv', "rb");
Another option: use os.path.join:
out = os.path.abspath(os.path.join('path', 'test.csv'))
Your problem is here:
'F:\Study\CEN\Mini Project\Data Sets\test.csv'
^^
Because you did not use a raw string, Python thinks \t is supposed to mean a tab character.
You can see that in the error message, by the way: Notice how Python translated all the backslashes into double backslashes (which is how a literal backslash needs to be represented in a normal string) in all the places except the one where "backslash plus letter" actually meant something special?
Use
ifile = open(r'F:\Study\CEN\Mini Project\Data Sets\test.csv', "rb")
(and remove the semicolons, you don't need them in Python) and it should work.
Your problem is with the "\t" AND a lack of exposure to various tools in the os.path package
The correct and easiest way to deal with this problem is to use os.path.normpath, combined with the string literal r, which ensures that backslashes are not interpreted as an escape character.
(Documentation on Lexical Analysis in python can be found here: https://docs.python.org/2/reference/lexical_analysis.html)
Open interactive python by typing "python" at the command line, and do the following to see that it's dead simple.
>>> import os
>>> path = r'F:\Study\CEN\Mini Project\Data Sets\test.csv'
>>> os.path.normpath(path)
'F:\\Study\\CEN\\Mini Project\\Data Sets\\test.csv'
normpath should be used when using hardcoded paths for scripts that may have to run on both dos and unix (eg OS X). It will ensure that the right kind of slashes are used for your particular environment
On a side note, if you are working with CSV files, you should use the petl library instead of the csv module. You'll save yourself a lot of time and hassle. Install it with pip install petl

os.path.isdir() returns False even when folder exists

I'm currently writing a script which has to check if all specified folders actually exist.
I found out I have to use os.path.isdir() with absolute paths.
I have the following directory structure:
X:\
pythonscripts\
files\
Films\
Series\
src\
When I open op my python command line and try if the folders actually exist, I get the following:
>>> import os
>>> os.path.isdir('X:\pythonscripts\src')
True
>>> os.path.isdir('X:\pythonscripts\files')
False
>>> os.path.isdir('X:\pythonscripts\files\Films')
False
>>> os.path.isdir('X:\pythonscripts\files\Series')
False
Which is odd, because when I copy and paste these paths into Windows Explorer, I can access them without problems. I checked permissions and all folders have the same permissions on them. Does anyone know what I'm doing wrong?
Escape backslash (\)
os.path.isdir('X:\\pythonscripts\\src')
or use raw string:
os.path.isdir(r'X:\pythonscripts\src')
without escape, you get wrong path:
>>> '\f'
'\x0c'
>>> print '\f'
>>> print '\\f'
\f
>>> print r'\f'
\f
Rather than use \, you might want to use the os.path.sep so that your code works on other platforms, then you don't have to escape these either.
When you are using
os.path.normpath(your_path)
you get rit of frontslash/backslash problemens. (But it can change the meaning, so just know what you are doing. But for normal paths there is no problem)
https://docs.python.org/3.6/library/os.path.html#os.path.normpath
Works very well :)

Categories