python:将“反斜杠双引号"字符串写入文件 [英] python: write 'backslash double-quote' string into file

查看:111
本文介绍了python:将“反斜杠双引号"字符串写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入文件,其中有一些包含双引号的字符串,并且想用Python生成C样式的头文件.

I've got an input file with some string containing double quotes in it, and want to generate a C-style header file with Python.

input file: Hello "Bob"
output file: Hello \"Bob\"

我无法编写代码来获取这样的文件,这是我到目前为止尝试过的:

I can't write the code to obtain such a file, here's what I've tried so far:

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

输出文件始终包含:

Hello \\\"Bob\\\"

我将 \ n \ t 字符串写入输出文件没有问题.

I had no problems writing \n, \t strings into the output file.

似乎我只能写零或两个反斜杠,有人可以帮忙吗?

It seems I can only write zero or two backslashes, can someone help please ?

推荐答案

您需要对双引号和反斜杠进行转义.以下对我有用(使用Python 2.7):

You need to escape both the double-quote and the backslash. The following works for me (using Python 2.7):

with open('temp.txt', 'r') as f:
    data = f.read()

with open('temp2.txt', 'w') as g:
    g.write(data.replace('\"', '\\\"'))

这篇关于python:将“反斜杠双引号"字符串写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆