python: write 'backslash double-quote' string into file -


i've got input file string containing double quotes in it, , want generate c-style header file python.

say,

input file: hello "bob" output file: hello \"bob\" 

i can't write code obtain such file, here's i've tried far:

key = 'key' val = 'hello "bob"' buf_list = list() ... val = val.replace('"', b'\x5c\x22') # tried: val = val.replace('"', r'\"') # tried: val = val.replace('"', '\\"') buf_list.append((key + '="' + val + '";\n').encode('utf-8')) ... keyval in buf_list:     lang_file.write(keyval) lang_file.close() 

the output file contains:

hello \\\"bob\\\" 

i had no problems writing \n, \t strings output file.

it seems can write 0 or 2 backslashes, can please ?

you need escape both double-quote , backslash. following works me (using python 2.7):

with open('temp.txt', 'r') f:     data = f.read()  open('temp2.txt', 'w') g:     g.write(data.replace('\"', '\\\"')) 

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -