paolo2988
paolo2988

Reputation: 867

Write escape characters to file

I need to write in a file some text that contains some string with escape characters.

My problem is that implicit special character like a new line or a tabulation effect have to hold their behavior when the text is printed.

But the text that contains special character is to be printed as simple text.

I can't add a \\ because this text is coming at runtime time and I don't know where these characters are.

An example:

header = """

newLineSymbol = '\n'


newValueSeparator = '\t'
"""

In my file I need to find:

newLineSymbol = '\n'


newValueSeparator = '\t'

I tried to open the file as binary to write with no success.

Last attempt to write the text using repr function, but it prints my text as:

\n\nnewLineSymbol = '\n'\n\n\nnewValueSeparator = '\t'\n

I use this to write:

fopen = open('output', 'w')
fopen.write(header)
fopen.close()

Upvotes: 2

Views: 3099

Answers (2)

Eric
Eric

Reputation: 254

you could try some string formatting like this:

    header = """

    newLineSymbol = '%s%s'


    newValueSeparator = '%s%s'
    """ % ('\\', 'n', '\\','t')

    fopen = open('output.txt', 'w')
    fopen.write(header)
    fopen.close()

Using the placeholders seems to work in this example, but I'm not sure how well it will work with other examples. Hopefully, this will help with some other ideas though.

Upvotes: 0

Anmol Singh Jaggi
Anmol Singh Jaggi

Reputation: 8576

What you want to do is impossible.

See this answer for the reason.
Quoting the answer:

After you type testStr = "\n" the special characters are already being interpreted. So in the next line you cannot change their interpretation as it already has happened. This is being done during lexical analysis stage, so even way before the code is actually executed. When the string is being assigned to your variable the two characters "\" and "n" are already gone - there is only one character - the new line character.

In short, once the string has been declared, there is no difference between '\n' and an actual <enter> in the multiline string.

Upvotes: 1

Related Questions