Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

python - write escaped character to file so that the character is visible

I want to write "" to a file. Not a "tab character", but literally "". How do I do this? It has been driving me crazy for more than an hour; everything I try produces an actual "tab character" (empty space).

Why would I want this? Because I'm generating a config file with a ConfigParser() which also includes some delimiters, and I want that file to be human-readable. I do not consider empty space readable.

EDIT: sorry, the problem was not clear: I want to do this for variables that contain strings. So writing "\t" is not an option. I must write the value of a variable containing an escaped character to a file in a manner ideologically equivalent to:

v = ""
write(v)

without changing the definition of v (though operations on v are OK) It seems impossible to change v into "\t" after it has been defined as "".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to escape the backslash so it won't be interpreted as a special character:

file_handle.write("\t")

EDIT: It looks like your best option will be to use python's excellent string.replace() function:

>>> v = "aaa  bbb"
>>> print v
aaa      bbb
>>> x = v.replace("", "\t")  # <-- replace all '' in string with '\t'
>>> print x
aaa  bbb

Note: v will be unchanged, since strings are immutable in python

EDIT 2:

Looks like converting to a raw string will take care of escapeing all escaped characters for you:

>>> a = 'aaa
bbb
ccc'
>>> print a
aaa
bbb
        ccc
>>> b = a.encode('string-escape')
>>> print b
aaa
bbb
ccc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...