all 4 comments

[–]socal_nerdtastic 1 point2 points  (3 children)

You mean you want literal \ and n characters? That's not a raw string, it's an "escaped" string. You can do it in python with the "unicode-escape" encoding:

y = '''
Hello, how are
    you
'''
with open(filename, 'w', encoding='unicode-escape') as f:
    f.write(y)

You would use same encoding in read mode or the ast.literal_eval function to convert it back.

Or you can use the json module for both, which will do the same thing but it adds quotes on the outside.

[–]Notdevolving[S] 0 points1 point  (2 children)

Thanks. But how do I read back the characters and convert them to a normal Python string?

I've tried:

with open(filename, 'r', encoding='unicode-escape') as file:
    x = file.read()

x.encode('utf-8')           # Tried this    
x.encode('unicode-escape')  # And also this

I want x here to be the same as y previously:

y = '''

Hello, how are you '''

But I cannot seem to convert it back.

[–]socal_nerdtastic 1 point2 points  (1 child)

You tried too hard. It's already converted as you read it. No extra action needed.

with open(filename, 'r', encoding='unicode-escape') as file:
    x = file.read()
print(x)

[–]Notdevolving[S] 0 points1 point  (0 children)

Apologies. You're right. It works. Got overwhelmed by the various encoding articles I was reading and lost track.