Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read blackslashes from a file correctly?

Tags:

python

file-io

The following code:

key = open("C:\Scripts\private.ppk",'rb').read()

reads the file and assigns its data to the var key.

For a reason, backslashes are multiplied in the process. How can I make sure they don't get multiplied?

like image 299
iTayb Avatar asked Dec 09 '22 08:12

iTayb


2 Answers

You ... don't. They are escaped when they are read in so that they will process properly when they are written out / used. If you're declaring strings and don't want to double up the back slashes you can use raw strings r'c:\myfile.txt', but that doesn't really apply to the contents of a file you're reading in.

>>> s = r'c:\boot.ini'
>>> s
'c:\\boot.ini'
>>> repr(s)
"'c:\\\\boot.ini'"
>>> print s
c:\boot.ini
>>>

As you can see, the extra slashes are stored internally, but when you use the value in a print statement (write a file, test for values, etc.) they're evaluated properly.

like image 163
g.d.d.c Avatar answered Dec 29 '22 00:12

g.d.d.c


You should read this great blog post on python and the backslash escape character.

And under some circumstances, if Python prints information to the console, you will see the two backslashes rather than one. For example, this is part of the difference between the repr() function and the str() function.

myFilename = "c:\newproject\typenames.txt" print repr(myFilename), str(myFilename) produces

'c:\newproject\typenames.txt' c:\newproject\typenames.txt

like image 33
Michael Pryor Avatar answered Dec 28 '22 22:12

Michael Pryor