Python Converts the backslash followed by numbers into Unicode - python

I have a string which is a Windows path returned by another function. The function returns the path with a single backslash within it. Here I can't using raw string conversion to a variable. re.escape(path) does not work either. path.replace('\','\\') throws SyntaxError: unexpected character after line continuation character
The function returns a path something like "D:\Data\201909\Foo\20190927c\Files" which gets coverted into "D:\\Data\ΓΌ909\\Foo\x8190927c\\Files"
path can be assumed as the variable containing the value returned by the function.
Could you please suggest me a solution for this.
Thanks Much !

The below solution worked for me.
path = r"{}" .format(path)
where new variable path is the converted raw string.

Related

Changing file path and need for raw? [duplicate]

This question already has answers here:
What exactly do "u" and "r" string prefixes do, and what are raw string literals?
(7 answers)
Closed 1 year ago.
import os
cwd = os.getcwd()
print("Current working directory: {0}".format(cwd))
# Print the type of the returned object
print("os.getcwd() returns an object of type: {0}".format(type(cwd)))
os.chdir(r"C:\Users\ghph0\AppData\Local\Programs\Python\Python39\Bootcamp\PDFs")
# Print the current working directory
print("Current working directory: {0}".format(os.getcwd()))
Hi all, I was changing my file directory so I could access specific files and was then greeted with this error:
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
From there I did some research and was told that converting the string to raw would fix the problem. My question is why do I convert it to raw and what does it do and why does it turn the file path into a red colour(not really important but never seen this before). Picture below:
https://i.stack.imgur.com/4oHlC.png
Many thanks to anyone that can help.
Backslashes in strings have a specific meaning in Python and are translated by the interpreter. You have surely already encountered "\n". Despite taking two letters to type, that is actually a one-character string meaning "newline". ANY backslashes in a string are interpreted that way. In your particular case, you used "\U", which is the way Python allows typing long Unicode values. "\U1F600", for example, is the grinning face emoji.
Because regular expressions often need to use backslashes for other uses, Python introduced the "raw" string. In a raw string, backslashes are not interpreted. So, r"\n" is a two-character string containing a backslash and an "n". This is NOT a newline.
Windows paths often use backslashes, so raw strings are convenient there. As it turns out, every Windows API will also accept forward slashes, so you can use those as well.
As for the colors, that probably means your editor doesn't know how to interpret raw strings.

Python: Image's path as a raw string an input to a function

Python: I want to get an image as an input from the user as a raw string! I used input() to get the path. Giving it as a raw string makes the program work, I can do it by appending r before the path, but Image.open(' ') also takes r as a string and producing an error. Can someone help me in resolving this problem.
path=input('Please enter the path of the image')
im=Image.open(path)
get an error as no file found
if i give..
y='r'+path
im=Image.open(y)
then the error is
OSError: [Errno 22] Invalid argument: 'rC:\\Users\\User\\Desktop\.......jpeg'
I am new to python, so please help me if there is any method by which I can solve this issue.
raw strings are for a programmer's convenience; you don't have to have your users enter raw strings as normal input.
See the end of this post for the solution to your problem. Because you said you are new to Python, I have decided to give a detailed answer here.
Why raw strings?
Normal strings assign special meaning to the \ (backslash) character. This is fine as \ can be escaped by using \\ (two backslashes) to represent a single backslash.
However, this can sometimes become ugly.
Consider, for example, a path: C:\Users\Abhishek\test.txt. To represent this as a normal string in Python, all \ must be escaped:
string = 'C:\\Users\\Abhishek\\test.txt'
You can avoid this by using raw strings. Raw strings don't treat \ specially.
string = r'C:\Users\Abhishek\test.txt'
That's it. This is the only use of raw strings, viz., convenience.
Solution
If you are using Python 2, use raw_input instead of input. If you are using Python 3 (as you should be) input is fine. Don't try to input the path as a raw string.

pushing a list to a file in python

I have a list like this
dis=('a','b','c',100)
I want it to push to a .Csv file(plan_to_prod2) ,but my folder name is a integer
my_df = pd.DataFrame(dis)
my_df.to_csv('E:\23\4\plan_to_prod2.csv')
i am getting invalid file name as error even though my file name is correct
You should use a raw string literal.
A \ followed by an integer is interpreted as a unicode character which is an invalid file name. Try print('E:\23\4\plan_to_prod2.csv') and see the output (I would have pasted it here but these characters don't show up when the answer is rendered). You can also see the problem in the error you provided in the comment.
When using raw string:
print(r'E:\23\4\plan_to_prod2.csv')
# E:\23\4\plan_to_prod2.csv
Instead of using raw string you can also use double slashes, ie print('E:\\23\\4\\plan_to_prod2.csv') but I find using raw strings much easier.
The \ character is used for escapes. So when you try to find the path you escape.
You should use / or use raw string r'' instead of \. Also, you could escape those backslashes by escaping it with an additional \.Choose whichever suits you best.
r'E:\23\4\plan_to_prod2.csv'
'E:\\23\\4\\plan_to_prod2.csv'
'E:/23/4/plan_to_prod2.csv'

Am I changing directories properly in Python?

I'm trying to figure out how to compile a github project with Python. I imported my os, but I am getting a syntax error when I attempt to change directories with this code: os.chdir(C:\Users\User\Desktop\Folder)
After doing that, I get this:
>>> os.chdir(C:\Users\User\Desktop\Folder)
File "<stdin>", line 1
os.chdir(C:\Users\User\Desktop\Folder)
^
SyntaxError: invalid syntax
I see that it is pointing at the colon. Am I putting in the directory incorrectly? (I have never used python in my life.) Any help would be greatly appreciated. Thanks in advance!
You need to pass it a string. And because it's a Windows path, it should be a raw string (Quote mark prefixed with r, like r''), so the backslashes don't get interpreted as string literal escapes (raw strings are more succinct than the alternative of doubling all the backslashes), making it:
os.chdir(r'C:\Users\User\Desktop\Folder')

Explicitly make a string into raw string

I am reading reading path to the registry from a text file. The registry path is
HKEY_LOCAL_MACHINE\Software\MYAPP\6.3
I store this registry in a variable :
REGISTRY_KEY
Then I strip the HKEY_LOCAL_MACHINE part from the string and try to read the value at the key.
if REGISTRY_KEY.split('\\')[0] == "HKEY_LOCAL_MACHINE":
keyPath = REGISTRY_KEY.strip("HKEY_LOCAL_MACHINE\\")
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, keyPath)
value = winreg.QueryValueEx(key, "InstallPath")[0]
except IOError as err:
print(err)
I get the following error
[WinError 2] The system cannot find the file specified
However if I do it manually like
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r'Software\MYAPP\6.3')
OR
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,"Software\\MYAPP\\6.3")
it works.
So is there any way I can make the keyPath variable to either be a raw string or contain double '\'
PS:I am using Python 3.3
A raw str is a way of entering the string so you do not need to escape special characters. Another way to enter the same str is to escape the special characters (blackslash being one of them). They would have the same data. So really your question doesn't have an answer.
You are also using strip incorrectly, but it would not matter for this particular string. Because the first character after the first \ is S and S is not in your strip command and your key ends in a digit also not in your strip command. But you will want to fix it so other keys are not messed up by this. You got lucky on this string.
>>> r"HKEY_LOCAL_MACHINE\Software\MYAPP\6.3".strip("HKEY_LOCAL_MACHINE\\")
'Software\\MYAPP\\6.3'
As for your real problem. There is something else about the string that is wrong. Try print repr(keyPath) before your call to OpenKey
EDIT: looks like SylvainDefresne guessed correctly about a newline character on the end of the string
Your REGISTRY_KEY.strip() call is not doing what you think it's doing. It doesn't remove the string HKEY_LOCAL_MACHINE\ from the beginning of the string. Instead, it removes the characters H, K, E, etc., in any order, from both ends of the string. This is why it works when you manually put in what you expect.
As for your original question, a double backslash is an escape sequence that produces a single backslash in your string, so it is not necessary to convert keyPath to double slashes.

Categories