Search code examples
python-3.xencodingutf-8bytebackslash

How do I get a working backslash in python


I have an encoded string saved as a string in a file, it is possible to change that, if it works then. I wanna read it and get the real string back. Sorry I'm not good in explaining xD, here's my code:

def saveFile(src, con):
    with open(src, "w") as f:
        f.write(str(con))
        f.close()

...
string = "юра"
saveFile("info", mlistsaver.encode())

this is the 'info' File:` b'\xd1\x8e\xd1\x80\xd0\xb0' but when I use this:

def get(src):
    f = src
    if path.isfile(f):
        with open(f, "r") as f:
            return f.read()
    else:
        return None

...


get("info").encode('iso-8859-1').decode('utf-8')

the string is just: b'\xd1\x8e\xd1\x80\xd0\xb0' I know it has to do something with double \ but I couldn't fix it. As already said I can save the string in whatever format you want, I think the way I did it is really stupid.

Thank you guys!


Solution

  • Thank you very much BpY and lenz, it's working now, here's my code:

    def saveFile(src, con):
        with open(src, "wb") as f:
            f.write(con)
            f.close()
    
    def get(src):
        f = src
        if path.isfile(f):
            with open(f, "rb") as f:
                return f.read()
        else:
            return None
    
    ...
    
    info="юра"
    saveFile("info", info.encode())
    print(get("info").decode("utf-8"))
    

    Output is: юра

    Again thank you and have a nice day:)