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.
Related
This question already has answers here:
How to fix "<string> DeprecationWarning: invalid escape sequence" in Python?
(2 answers)
Closed 4 years ago.
In the given example: "\info\more info\nName"
how would I turn this into bytes
I tried using unicode-escape but that didn't seem to work :(
data = "\info\more info\nName"
dataV2 = str.encode(data)
FinalData = dataV2.decode('unicode-escape').encode('utf_8')
print(FinalData)
This is were I should get b'\info\more info\nName'
but something unexpected happens and I get DeprecationWarnings in my terminal
I'm assuming that its because of the backslashes causing a invalid sequence but I need them for this project
Backslashes before characters indicate an attempt to escape the character that follows to make it into a special character of some sort. You get the DeprecationWarning because Python is (finally) going to make unrecognized escapes an error, rather than silently treating them as a literal backslash followed by the character.
To fix, either double your backslashes (not sure if you intended a newline; if so, double double the backslash before the n):
data = "\\info\\more info\\nName"
or, if you want all the backslashes to be literal backslashes (the \n shouldn't be a newline), then you can use a raw string by prefixing with r:
data = r"\info\more info\nName"
which disables backslashes interpolation for everything except the quote character itself.
Note that if you just let data echo in the interactive interpreter, it will show the backslashes as doubled (because it implicitly uses the repr of the str, which is what you'd type to reproduce it). To avoid that, print the str to see what it would actually look like:
>>> "\\info\\more info\\nName" # repr produced by simply evaluating it, which shows backslashes doubled, but there's really only one each time
"\\info\\more info\\nName"
>>> print("\\info\\more info\\nName") # print shows the "real" contents
\info\more info\nName
>>> print("\\info\\more info\nName") # With new line left in place
\info\more info
Name
>>> print(r"\info\more info\nName") # Same as first option, but raw string means no doubling backslashes
\info\more info\nName
You can escape a backslash with another backslash.
data = "\\info\\more info\nName"
You could also use a raw string for the parts that don't need escapes.
data = r"\info\more info""\nName"
Note that raw strings don't work if the final character is a backslash.
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'
I have a dictionary with some strings, in one of the string there are two backslashes. I want to replace them with a single backslash.
These are the backslashes: IfNotExist\\u003dtrue
Configurations = {
"javax.jdo.option.ConnectionUserName": "test",
"javax.jdo.option.ConnectionDriverName": "org.mariadb.jdbc.Driver",
"javax.jdo.option.ConnectionPassword": "sxxxsasdsasad",
"javax.jdo.option.ConnectionURL": "jdbc:mysql://hive-metastore.cr.eu-west-1.rds.amazonaws.com:3306/hive?createDatabaseIfNotExist\\u003dtrue"
}
print (Configurations)
When I print it keeps showing the two backslashes. I know that the way to escape a backslash is using \ this works in a regular string but it does not work in a dictionary.
Any ideas?
The problem comes from the encoding.
In fact \u003d is the UNICODE representation of =.
The backslash is escaped by another backslash which is a good thing.
You may need to:
Replace \u003d as =
Read it as unicode then you should prepend the string with u like u"hi \\u003d" may be ok
Printing the dictionary shows you a representation of the dictionary object. It doesn't necessarily show you a nice representation of everything inside it. To do that you need to do:
for value in Configurations.values():
print(value)
When you print out your dictionary using
print (Configurations), it will print out the repr() value of the dictionary
You will get
{'javax.jdo.option.ConnectionDriverName': 'org.mariadb.jdbc.Driver', 'javax.jdo.option.ConnectionUserName': 'test', 'javax.jdo.option.ConnectionPassword': 'sxxxsasdsasad', 'javax.jdo.option.ConnectionURL': 'jdbc:mysql://hive-metastore.cr.eu-west-1.rds.amazonaws.com:3306/hive?createDatabaseIfNotExist\\u003dtrue'}
You need to print out your dictionary with
print (Configurations["javax.jdo.option.ConnectionURL"])
or
print (str(Configurations["javax.jdo.option.ConnectionURL"]))
Note: str() is added
Then the output will be
jdbc:mysql://hive-metastore.cr.eu-west-1.rds.amazonaws.com:3306/hive?createDatabaseIfNotExist\u003dtrue
For more detail check Python Documentation - Fancier Output Formatting
The str() function is meant to return representations of values which
are fairly human-readable, while repr() is meant to generate
representations which can be read by the interpreter (or will force a
SyntaxError if there is no equivalent syntax).
If you want to represent that string by using a single backslash instead of a double backslash, then you need the str() representation, not the repr(). When you print a dictionary, you always get the repr() of the included strings.
You can print the str() by formatting the dictionary yourself, like so:
print ( "{" +
', '.join("'{key}': '{value}'".format(key=key, value=value)
for key, value in Configurations.items()) +
"}")
Depending on how you print your string, Python will print two backslashes where the string actually only has one in it. This is Python's way of indicating that the backslash is an actual backslash, and not part of an escaped character; because print will actually show you '\n' for a carriage return, for example.
Try writing the string to a file and then opening the file in an editor.
(Linux..)
> f = open('/tmp/somefile.txt', 'w')
> f.write(sometextwithbackslashes)
> \d
$ vi /tmp/somefile.txt
I am supposed to decode the string below in a script I have made (it is a task from a webpage). In order to ensure that the decoded word will be correct, I can not change the string in any way. Since the quote marks affects the string, parts like q90:;AI is not a string, which results in a syntax error.
q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a
Is there a way I can decode the encrypted message without changing it? As of now I am just getting syntax error when I define the string in a variable.
You can surround the string with single quotes, since double quotes are used in the string already:
>>> print 'q0Ø:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GØ""N6K086HB"Ø8CRHW"+LS79Ø""N29QCLN5WNEBS8GENBG4FØ47a'
q0Ã:;AI"E47FRBQNBG4WNB8B4LQN8ERKC88U8GEN?T6LaNBG4GÃ""N6K086HB"Ã8CRHW"+LS79Ã""N29QCLN5WNEBS8GENBG4FÃ47a
>>>
I want to convert a string, which contains a file path, to a raw string, so the '\' characters are not considered escapes.
folderList = os.listdir(folderPath)
# folderList is a list of files, path = folderPath + (element of folderList)
So if I'm using something like this in Python 3, can I convert path to a raw string? I've tried using the encode method for strings, but that does not work. Also, I am not looking for solutions to replace the string '\' with '\'. I feel this process would take too long for how many paths I would have to process. So are there any simple conversions to convert path into a raw string?
As per the Python 3 documentation:
Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters.
So in your case, path = r'c:\Users' should suffice.
If the data is already stored in a variable then it's important to realise that it already is a raw string. The \ character is used only to help you represent escaped characters in string literals. So;
>>> r'c:\Users' == 'c:\\Users'
True
From what you describe, therefore, you don't have anything to do.
Yes there is a simple solution to this, you can try using path = r'c:\Users' or you can also use path = 'c:\\Users' whichever you feel like